阿里云IOT设备管理

发布于:2025-02-16 ⋅ 阅读:(31) ⋅ 点赞:(0)

        本文主要介绍了阿里云IOT设备管理的基本概念、功能特点以及应用场景。阐述了如何利用阿里云IOT平台实现设备的连接、监控和控制,以及如何借助其丰富的数据分析功能提升设备管理效率。


一、IOT工作原理

二、创建模拟设备

1.创建产品

2.物模型

3.设备

4.设备数据上报

因为是模拟设备,这里通过node进行模拟数据的上报,下面代码为bracelet_001.js案列代码

const mqtt = require('aliyun-iot-mqtt');
// 1. 设备身份信息
var options = {
  productKey: "j0rk1AN61hM",
  deviceName: "watch001",
  deviceSecret: "ea94110e5495bb04b0a7b35b9535a50c",
  host: "iot-06z00frq8umvkx2.mqtt.iothub.aliyuncs.com"
};

// 2. 建立MQTT连接
const client = mqtt.getAliyunIotMqttClient(options);
//订阅云端指令Topic
client.subscribe(`/${options.productKey}/${options.deviceName}/user/get`)
client.subscribe(`/sys/${options.productKey}/${options.deviceName}/thing/event/property/post_reply`)
client.on('message', function (topic, message) {
  console.log("topic " + topic)
  console.log("message " + message)
})

setInterval(function () {
  // 3.定时上报温湿度数据
  client.publish(`/sys/${options.productKey}/${options.deviceName}/thing/event/property/post`, getPostData(), { qos: 0 });
}, 5 * 1000);

var power = 1000;

function getPostData () {
  const payloadJson = {
    id: Date.now(),
    version: "1.0",
    params: {
      PowerConsumption: power--
    },
    method: "thing.event.property.post"

  }
  console.log("payloadJson " + JSON.stringify(payloadJson))
  return JSON.stringify(payloadJson);
}

在bracelet_001.js目录下cmd打开运行窗口,运行下面命令

npm install aliyun-iot-mqtt

node bracelet_001.js

三、IOT接口对接

1.依赖引入

<!-- https://mvnrepository.com/artifact/com.aliyun/iot20180120 -->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>iot20180120</artifactId>
            <version>3.0.8</version>
        </dependency>

        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>tea-openapi</artifactId>
            <version>0.2.2</version>
        </dependency>

2.环境配置

zzyl:
  aliyun:
    accessKeyId: LTAI5tDQKg9F61aJhbmhqVRK
    accessKeySecret: LYUKZH7HQGBoD025pmSq0fQsREaOYD
    consumerGroupId: DEFAULT_GROUP
    regionId: cn-shanghai
    iotInstanceId: iot-06z00frq8umvkx2
    host: iot-06z00frq8umvkx2.amqp.iothub.aliyuncs.com

3.读取配置类

@Data
@Configuration
@ConfigurationProperties(prefix = "zzyl.aliyun")
public class AliIoTConfigProperties {

    /**
     * 访问Key
     */
    private String accessKeyId;
    /**
     * 访问秘钥
     */
    private String accessKeySecret;
    /**
     * 区域id
     */
    private String regionId;
    /**
     * 实例id
     */
    private String iotInstanceId;
    /**
     * 域名
     */
    private String host;

    /**
     * 消费组
     */
    private String consumerGroupId;

}

4.连接配置类

import com.aliyun.iot20180120.Client;
import com.aliyun.teaopenapi.models.Config;
import com.zzyl.properties.AliIoTConfigProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class IotClientConfig {

    @Autowired
    private AliIoTConfigProperties aliIoTConfigProperties;
    
    @Bean
    public Client instance() throws Exception {
        Config config = new Config();
        config.accessKeyId = aliIoTConfigProperties.getAccessKeyId();
        config.accessKeySecret = aliIoTConfigProperties.getAccessKeySecret();
        // 您的可用区ID 默认上海
        config.regionId = aliIoTConfigProperties.getRegionId();
        return new Client(config);
    }
}

5.测试类

@SpringBootTest
public class IoTDeviceTest {


    @Autowired
    private Client client;

    @Autowired
    private AliIoTConfigProperties aliIoTConfigProperties;

    /**
     * 查询公共实例下的所有产品
     * @throws Exception
     */
    @Test
    public void selectProduceList() throws Exception {
        QueryProductListRequest queryProductListRequest = new QueryProductListRequest();
        queryProductListRequest.setCurrentPage(1);
        queryProductListRequest.setPageSize(10);
        queryProductListRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryProductListResponse queryProductListResponse = client.queryProductList(queryProductListRequest);
        System.out.println(queryProductListResponse.getBody().getData());
    }
}

四、业务对接

IOT官方文档:调用QueryProductList接口查看所有产品列表_物联网平台(IoT)-阿里云帮助中心

1.查询所有的产品

@PostMapping("/QueryProductList")
    @ApiOperation(value = "查看所有的产品列表")
    public ResponseResult queryProductList(@RequestBody QueryProductListRequest queryProductListRequest) throws Exception{
        queryProductListRequest.setIotInstanceId(iotInstanceId);
        QueryProductListResponse queryProductListResponse = client.queryProductList(queryProductListRequest);
        if (Objects.isNull(queryProductListResponse.getBody())) {
            return ResponseResult.error();
        }
        return ResponseResult.success(queryProductListResponse.getBody().getData());
    }

2.注册设备

 @Override
    public void registerDevice(DeviceDto deviceDto) throws Exception {
        //请求IOT中新增设备
//        RegisterDeviceRequest registerDeviceRequest = new RegisterDeviceRequest();
        RegisterDeviceRequest registerDeviceRequest = deviceDto.getRegisterDeviceRequest();
        registerDeviceRequest.setProductKey(deviceDto.getProductKey());
        registerDeviceRequest.setIotInstanceId(iotInstanceId);
        RegisterDeviceResponse registerDeviceResponse = client.registerDevice(registerDeviceRequest);
        //是否新增成功
        if (!registerDeviceResponse.getBody().getSuccess()) {
            throw new Exception("新增设备失败");
        }
        //查询产品名称
        QueryProductRequest queryProductRequest = new QueryProductRequest();
        queryProductRequest.setProductKey(deviceDto.getProductKey());
        queryProductRequest.setIotInstanceId(iotInstanceId);
        QueryProductResponse queryProductResponse = client.queryProduct(queryProductRequest);
        String productName = queryProductResponse.getBody().getData().getProductName();
        //新增设备
        Device device = new Device();
        BeanUtils.copyProperties(deviceDto, device);
        //设备id
        device.setDeviceId(registerDeviceResponse.getBody().getData().getIotId());
        //备注名称
        device.setNoteName(deviceDto.getNickname());
        //产品key
        device.setProductId(deviceDto.getProductKey());
        //产品名称
        device.setProductName(productName);
        //绑定位置
        device.setBindingLocation(deviceDto.getBindingLocation().toString());
        //判断设备接入类别
        if(Objects.equal(device.getLocationType(), 0)) {
            device.setPhysicalLocationType(-1);
        }
        //添加设备信息到数据库
        try {
            deviceMapper.insert(device);
            log.info("添加设备成功");
        } catch (Exception e) {
            //删除IOT中的设备
            DeleteDeviceRequest deleteDeviceRequest = new DeleteDeviceRequest();
            deleteDeviceRequest.setIotInstanceId(iotInstanceId);
            deleteDeviceRequest.setProductKey(device.getProductKey());
            deleteDeviceRequest.setDeviceName(device.getDeviceName());
            deleteDeviceRequest.setIotId(device.getDeviceId());
            client.deleteDevice(deleteDeviceRequest);
            throw new RuntimeException("该老人/位置已绑定该产品,请重新选择");
        }
    }

3.查询所有设备

/**
     * 查询设备
     */
    @Override
    public PageResponse<DeviceVo> queryDevice(QueryDeviceRequest request) throws Exception {
        //根据产品查询设备列表
        request.setIotInstanceId(iotInstanceId);
        QueryDeviceResponse queryDeviceResponse = client.queryDevice(request);
        if (!queryDeviceResponse.getBody().getSuccess()) {
            throw new Exception("查询设备失败");
        }
        //取出所有的设备id
        List<QueryDeviceResponseBody.QueryDeviceResponseBodyDataDeviceInfo> deviceInfoList = queryDeviceResponse.getBody().getData().getDeviceInfo();
        List<String> deviceIdList = deviceInfoList.stream().map(QueryDeviceResponseBody.QueryDeviceResponseBodyDataDeviceInfo::getIotId)
            .collect(Collectors.toList());
        //根据id集合到DB中查询所有设备
        List<DeviceVo> deviceVos = deviceMapper.selectByDeviceIds(deviceIdList);
        //整合数据
        List<DeviceVo> deviceResult = new ArrayList<>();
        Map<String, DeviceVo> deviceVoMap = deviceVos.stream().collect(Collectors.toMap(DeviceVo::getDeviceId, deviceVo -> deviceVo));
        deviceInfoList.forEach(deviceInfo -> {
            DeviceVo deviceVo = deviceVoMap.get(deviceInfo.getIotId());
            if (deviceVo != null) {
                BeanUtils.copyProperties(deviceInfo, deviceVo);
                deviceResult.add(deviceVo);
            }
        });
        return PageResponse.of(deviceResult, request.getCurrentPage(), request.getPageSize(), (long) queryDeviceResponse.getBody().getPageCount(), (long)queryDeviceResponse.getBody().getTotal());
    }

4.查询设备的详细信息

/**
     * 查询指定设备的详细信息
     * @param request
     * @return
     * @throws Exception
     */
    @Override
    public DeviceVo queryDeviceDetail(QueryDeviceDetailRequest request) throws Exception {
        request.setIotInstanceId(iotInstanceId);
        QueryDeviceDetailResponse queryDeviceDetailResponse = client.queryDeviceDetail(request);
        if (Boolean.FALSE.equals(queryDeviceDetailResponse.getBody().getSuccess())) {
            throw new Exception(queryDeviceDetailResponse.getBody().getErrorMessage());
        }
        QueryDeviceDetailResponseBody.QueryDeviceDetailResponseBodyData deviceData = queryDeviceDetailResponse.getBody().getData();
        DeviceVo deviceVo = new DeviceVo();
        BeanUtils.copyProperties(deviceData, deviceVo);
        List<DeviceVo> devices = deviceMapper.selectByDeviceIds(Lists.newArrayList(deviceData.getIotId()));
        if (CollUtil.isNotEmpty(devices)) {
            BeanUtil.copyProperties(devices.get(0), deviceVo, CopyOptions.create().ignoreNullValue());
            deviceVo.setIotId(deviceVo.getDeviceId());
            return deviceVo;
        }
        return new DeviceVo();
    }

5.查询设备的状态

@PostMapping("/QueryDevicePropertyStatus")
    @ApiOperation(value = "查询指定设备的状态", notes = "查询指定设备的状态")
    public ResponseResult QueryDevicePropertyStatus(@RequestBody QueryDevicePropertyStatusRequest request) throws Exception {
       request.setIotInstanceId(iotInstanceId);
        QueryDevicePropertyStatusResponse queryDevicePropertyStatusResponse = client.queryDevicePropertyStatus(request);
        return ResponseResult.success(queryDevicePropertyStatusResponse.getBody().getData());
    }

6.查看物模型功能列表

@PostMapping("/QueryThingModelPublished")
    @ApiOperation(value = "查看指定产品的已发布物模型中的功能定义详情", notes = "查看指定产品的已发布物模型中的功能定义详情")
    public ResponseResult queryThingModelPublished(@RequestBody QueryThingModelPublishedRequest request) throws Exception {
        request.setIotInstanceId(iotInstanceId);
        QueryThingModelPublishedResponse response = client.queryThingModelPublished(request);
        return ResponseResult.success(response.getBody().getData());
    }

7.修改设备名称

    @Override
    public void updateDevice(DeviceDto deviceDto) throws Exception {
        BatchUpdateDeviceNicknameRequest request = new BatchUpdateDeviceNicknameRequest();
        request.setIotInstanceId(iotInstanceId);
        BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo nicknameInfo = BeanUtil.toBean(deviceDto, BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo.class);
        request.setDeviceNicknameInfo(Lists.newArrayList(nicknameInfo));
        BatchUpdateDeviceNicknameResponse response = client.batchUpdateDeviceNickname(request);
        // 保存位置
        if (Boolean.TRUE.equals(response.getBody().getSuccess())) {
            // 保存位置
            Device device = BeanUtil.toBean(deviceDto, Device.class);
            device.setProductId(deviceDto.getProductKey());
            device.setNoteName(deviceDto.getNickname());
            Device device1 = deviceMapper.selectByPrimaryKey(device.getId());
            if (ObjectUtil.isEmpty(device1)) {
                device.setDeviceId(deviceDto.getIotId());
                device.setNoteName(deviceDto.getNickname());
                device.setProductId(deviceDto.getProductKey());
                device.setDeviceId(deviceDto.getIotId());
                deviceMapper.insert(device);
                return;
            }
            try {
                deviceMapper.updateByPrimaryKeySelective(device);
            }catch (Exception e) {
                throw new BaseException("该老人/位置已绑定该产品,请重新选择");
            }
            return;
        }
        throw new BaseException(response.getBody().getErrorMessage());
    }

8.删除设备

@Override
    public void deleteDevice(DeleteDeviceRequest request) throws Exception {
        request.setIotInstanceId(iotInstanceId);
        DeleteDeviceResponse response = client.deleteDevice(request);
        if (Boolean.TRUE.equals(response.getBody().getSuccess())) {
            deviceMapper.deleteByDeviceId(request.getIotId());
            return;
        }
        throw new BaseException(response.getBody().getErrorMessage());
    }


网站公告

今日签到

点亮在社区的每一天
去签到