添加客户端接口

V0.5.x
xiwa 2022-05-09 10:24:45 +08:00
parent e675bcf2d6
commit 477421031f
21 changed files with 292 additions and 130 deletions

View File

@ -10,6 +10,8 @@ public interface Constants {
String DEVICE_CACHE = "device_cache";
String SPACE_CACHE = "device_cache";
String THING_MODEL_CACHE = "thing_model_cache";
String WECHAT_APP_ID = "wx791cb7bf75950e0c";

View File

@ -30,14 +30,9 @@ public class DeviceCache {
return deviceRepository.findByProductKeyAndDeviceName(pk, dn);
}
@Cacheable(value = Constants.DEVICE_CACHE, key = "#deviceId")
public DeviceInfo findByDeviceId(String deviceId) {
return deviceRepository.findByDeviceId(deviceId);
}
@Cacheable(value = Constants.DEVICE_CACHE, key = "#deviceId")
public DeviceInfo get(String deviceId) {
return deviceRepository.findById(deviceId).orElse(new DeviceInfo());
return deviceRepository.findById(deviceId).orElse(null);
}
}

View File

@ -4,6 +4,12 @@ import cc.iotkit.model.space.Home;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface HomeRepository extends MongoRepository<Home, String> {
List<Home> findByUid(String uid);
Home findByUidAndCurrent(String uid,boolean current);
}

View File

@ -31,22 +31,17 @@ public class ProductCache {
return INSTANCE;
}
@Cacheable(value = Constants.PRODUCT_CACHE, key = "'pk'+#pk", unless = "#result == null")
@Cacheable(value = Constants.PRODUCT_CACHE, key = "'product'+#pk")
public Product findById(String pk) {
return productRepository.findById(pk).orElse(new Product());
}
@Cacheable(value = Constants.THING_MODEL_CACHE, key = "'pk'+#pk", unless = "#result == null")
@Cacheable(value = Constants.THING_MODEL_CACHE, key = "'thing_model'+#pk")
public ThingModel getThingModel(String pk) {
return thingModelRepository.findByProductKey(pk);
}
@Cacheable(value = Constants.PRODUCT_SCRIPT_CACHE, key = "'pk'+#pk", unless = "#result == null")
public ProductModel getProductScript(String pk) {
return productModelRepository.findById(pk).orElse(null);
}
@Cacheable(value = Constants.PRODUCT_SCRIPT_CACHE, key = "'model'+#model", unless = "#result == null")
@Cacheable(value = Constants.PRODUCT_SCRIPT_CACHE, key = "'product_script'+#model")
public ProductModel getProductScriptByModel(String model) {
return productModelRepository.findByModel(model);
}

View File

@ -0,0 +1,33 @@
package cc.iotkit.dao;
import cc.iotkit.common.Constants;
import cc.iotkit.model.space.Space;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;
import javax.annotation.PostConstruct;
@Repository
public class SpaceCache {
@Autowired
private SpaceRepository spaceRepository;
private static SpaceCache INSTANCE;
@PostConstruct
public void init() {
INSTANCE = this;
}
public static SpaceCache getInstance() {
return INSTANCE;
}
@Cacheable(value = Constants.SPACE_CACHE, key = "#spaceId")
public Space getSpace(String spaceId) {
return spaceRepository.findById(spaceId).orElse(null);
}
}

View File

@ -4,6 +4,13 @@ import cc.iotkit.model.space.SpaceDevice;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface SpaceDeviceRepository extends MongoRepository<SpaceDevice, String> {
List<SpaceDevice> findByUidOrderByUseAtDesc(String uid);
List<SpaceDevice> findByUidAndSpaceIdOrderByAddAtDesc(String uid, String spaceId);
}

View File

@ -4,6 +4,11 @@ import cc.iotkit.model.space.Space;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface SpaceRepository extends MongoRepository<Space, String> {
List<Space> findByUidOrderByCreateAtDesc(String uid);
}

View File

@ -51,6 +51,11 @@ public class CacheConfig {
Caffeine.newBuilder()
.expireAfterWrite(5, TimeUnit.MINUTES)
.build()
), new CaffeineCache(
Constants.SPACE_CACHE,
Caffeine.newBuilder()
.expireAfterWrite(5, TimeUnit.MINUTES)
.build()
)
));
return manager;

View File

@ -9,6 +9,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
@ -53,9 +54,11 @@ public class KeycloakSecurityConfig extends KeycloakWebSecurityConfigurerAdapter
super.configure(http);
http
.authorizeRequests()
.antMatchers("/*.html", "/favicon.ico","/v2/api-docs", "/webjars/**", "/swagger-resources/**", "/*.js").permitAll()
.antMatchers("/*.html", "/favicon.ico", "/v2/api-docs", "/webjars/**", "/swagger-resources/**", "/*.js").permitAll()
.antMatchers("/api/**").hasRole("iot_client_user")
.antMatchers("/aligenieDevice/invoke/**").hasRole("iot_client_user")
.antMatchers(HttpMethod.DELETE).hasRole("iot_write")
.antMatchers(HttpMethod.PUT).hasRole("iot_write")
.antMatchers("/**/save*/**").hasRole("iot_write")
.antMatchers("/**/del*/**").hasRole("iot_write")
.antMatchers("/**/add*/**").hasRole("iot_write")

View File

@ -1,22 +1,18 @@
package cc.iotkit.manager.controller;
import cc.iotkit.dao.*;
import cc.iotkit.manager.model.vo.SpaceDeviceVo;
import cc.iotkit.manager.model.vo.SpaceInfo;
import cc.iotkit.model.*;
import cc.iotkit.model.device.DeviceInfo;
import cc.iotkit.model.product.Product;
import cc.iotkit.model.space.SpaceDevice;
import cc.iotkit.common.exception.BizException;
import cc.iotkit.dao.HomeRepository;
import cc.iotkit.dao.SpaceRepository;
import cc.iotkit.manager.service.DataOwnerService;
import cc.iotkit.manager.utils.AuthUtil;
import cc.iotkit.model.space.Home;
import cc.iotkit.model.space.Space;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.Optional;
@RestController
@ -24,51 +20,76 @@ import java.util.stream.Collectors;
public class SpaceController {
@Autowired
private SpaceDeviceRepository spaceDeviceRepository;
private SpaceRepository spaceRepository;
@Autowired
private DeviceRepository deviceRepository;
private HomeRepository homeRepository;
@Autowired
private DeviceCache deviceCache;
@Autowired
private ProductCache productCache;
private DataOwnerService dataOwnerService;
// @PostMapping("/list")
// public Paging<SpaceInfo> getDevices(int page,
// int limit,
// String address) {
// Criteria condition = new Criteria();
// if (StringUtils.isNotBlank(address)) {
// condition.and("address").regex(".*" + address + ".*");
// }
// List<UserInfo> userInfoList = userInfoDao.find(condition, (page - 1) * limit,
// limit, Sort.Order.desc("createAt"));
//
// List<SpaceInfo> spaces = userInfoList.stream().map((u ->
// new SpaceInfo(u.getAddress(), u.getUid())))
// .collect(Collectors.toList());
//
// return new Paging<>(userInfoDao.count(condition),
// spaces);
// }
@PostMapping("/saveHome/{id}")
public void saveHome(@PathVariable("id") String id, Home home) {
Optional<Home> optHome = homeRepository.findById(id);
if (!optHome.isPresent()) {
throw new BizException("home does not exist");
}
Home oldHome = optHome.get();
dataOwnerService.checkOwner(oldHome);
if (StringUtils.isNotBlank(home.getName())) {
oldHome.setName(home.getName());
}
if (StringUtils.isNotBlank(home.getAddress())) {
oldHome.setName(home.getAddress());
}
homeRepository.save(oldHome);
}
@GetMapping("/{userId}/devices")
public List<SpaceDeviceVo> getDevices(@PathVariable("userId") String userId) {
List<SpaceDeviceVo> deviceVos = new ArrayList<>();
List<SpaceDevice> devices = spaceDeviceRepository.findAll(Example.of(SpaceDevice.builder().uid(userId).build()));
devices.forEach(sd -> {
DeviceInfo deviceInfo = deviceCache.findByDeviceId(sd.getDeviceId());
Product product = productCache.findById(deviceInfo.getProductKey());
deviceVos.add(SpaceDeviceVo.builder()
.deviceId(sd.getDeviceId())
.name(sd.getName())
.picUrl(product.getImg())
.spaceName(sd.getSpaceName())
.online(deviceInfo.getState().isOnline())
.property(deviceInfo.getProperty())
.productKey(deviceInfo.getProductKey())
.build());
});
return deviceVos;
/**
*
*/
@GetMapping("/spaces")
public List<Space> getSpaces() {
return spaceRepository.findByUidOrderByCreateAtDesc(AuthUtil.getUserId());
}
/**
*
*/
@PostMapping("/add")
public void addSpace(String name) {
String uid = AuthUtil.getUserId();
Home currHome = homeRepository.findByUidAndCurrent(uid, true);
if (currHome == null) {
throw new BizException("current home does not exist");
}
spaceRepository.save(Space.builder()
.homeId(currHome.getId())
.name(name)
.uid(uid)
.createAt(System.currentTimeMillis())
.build());
}
@DeleteMapping("/delSpace/{id}")
public void delSpace(@PathVariable("id") String id) {
checkExistAndOwner(id);
spaceRepository.deleteById(id);
}
@PostMapping("/saveSpace/{id}")
public void saveSpace(@PathVariable("id") String id, String name) {
Space oldSpace = checkExistAndOwner(id);
oldSpace.setName(name);
spaceRepository.save(oldSpace);
}
private Space checkExistAndOwner(String id) {
Optional<Space> optSpace = spaceRepository.findById(id);
if (!optSpace.isPresent()) {
throw new BizException("space does not exist");
}
dataOwnerService.checkOwner(optSpace.get());
return optSpace.get();
}
}

View File

@ -0,0 +1,119 @@
package cc.iotkit.manager.controller;
import cc.iotkit.dao.*;
import cc.iotkit.manager.model.vo.SpaceDeviceVo;
import cc.iotkit.manager.utils.AuthUtil;
import cc.iotkit.model.device.DeviceInfo;
import cc.iotkit.model.product.Product;
import cc.iotkit.model.space.Space;
import cc.iotkit.model.space.SpaceDevice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/space")
public class SpaceDeviceController {
@Autowired
private SpaceDeviceRepository spaceDeviceRepository;
@Autowired
private DeviceRepository deviceRepository;
@Autowired
private DeviceCache deviceCache;
@Autowired
private ProductCache productCache;
@Autowired
private SpaceCache spaceCache;
/**
* 使
*/
@GetMapping("/myRecentDevices")
public List<SpaceDeviceVo> getMyRecentDevices() {
List<SpaceDevice> spaceDevices = spaceDeviceRepository.findByUidOrderByUseAtDesc(AuthUtil.getUserId());
return spaceDevices.stream().map((this::parseSpaceDevice)).collect(Collectors.toList());
}
/**
* -
*
* @param spaceId id
*/
@GetMapping("/myDevices/{spaceId}")
public List<SpaceDeviceVo> getMyDevices(String spaceId) {
List<SpaceDevice> spaceDevices = spaceDeviceRepository.findByUidOrderByUseAtDesc(AuthUtil.getUserId());
return spaceDevices.stream().map((this::parseSpaceDevice)).collect(Collectors.toList());
}
private SpaceDeviceVo parseSpaceDevice(SpaceDevice sd) {
DeviceInfo device = deviceCache.get(sd.getDeviceId());
Space space = spaceCache.getSpace(sd.getSpaceId());
Product product = productCache.findById(device.getProductKey());
DeviceInfo.State state = device.getState();
return SpaceDeviceVo.builder()
.id(sd.getId())
.deviceId(sd.getDeviceId())
.deviceName(device.getDeviceName())
.name(sd.getName())
.spaceId(sd.getSpaceId())
.spaceName(space.getName())
.productKey(device.getProductKey())
.picUrl(product.getImg())
.online(state != null && state.isOnline())
.property(device.getProperty())
.uid(sd.getUid())
.build();
}
// @PostMapping("/list")
// public Paging<SpaceInfo> getDevices(int page,
// int limit,
// String address) {
// Criteria condition = new Criteria();
// if (StringUtils.isNotBlank(address)) {
// condition.and("address").regex(".*" + address + ".*");
// }
// List<UserInfo> userInfoList = userInfoDao.find(condition, (page - 1) * limit,
// limit, Sort.Order.desc("createAt"));
//
// List<SpaceInfo> spaces = userInfoList.stream().map((u ->
// new SpaceInfo(u.getAddress(), u.getUid())))
// .collect(Collectors.toList());
//
// return new Paging<>(userInfoDao.count(condition),
// spaces);
// }
@GetMapping("/{userId}/devices")
public List<SpaceDeviceVo> getDevices(@PathVariable("userId") String userId) {
List<SpaceDeviceVo> deviceVos = new ArrayList<>();
List<SpaceDevice> devices = spaceDeviceRepository.findAll(Example.of(SpaceDevice.builder().uid(userId).build()));
devices.forEach(sd -> {
DeviceInfo deviceInfo = deviceCache.get(sd.getDeviceId());
Product product = productCache.findById(deviceInfo.getProductKey());
deviceVos.add(SpaceDeviceVo.builder()
.deviceId(sd.getDeviceId())
.name(sd.getName())
.picUrl(product.getImg())
.spaceName("")
.online(deviceInfo.getState().isOnline())
.property(deviceInfo.getProperty())
.productKey(deviceInfo.getProductKey())
.build());
});
return deviceVos;
}
}

View File

@ -134,7 +134,7 @@ public class SpaceController {
List<SpaceDeviceVo> spaceDeviceVos = new ArrayList<>();
spaceDevices.forEach(sd -> spaceDeviceVos.add(buildSpaceDeviceVo(
sd.getId(), sd.getDeviceId(),
sd.getUid(), sd.getName(), sd.getSpaceName())));
sd.getUid(), sd.getName(), "")));
return spaceDeviceVos;
}
@ -146,7 +146,7 @@ public class SpaceController {
return buildSpaceDeviceVo(device.getId(), device.getDeviceId(),
AuthUtil.getUserId(), device.getName(),
device.getSpaceName());
"");
}
@ApiOperation("使用mac获取设备信息")
@ -170,7 +170,7 @@ public class SpaceController {
}
private SpaceDeviceVo buildSpaceDeviceVo(String id, String deviceId, String uid, String name, String spaceName) {
DeviceInfo deviceInfo = deviceCache.findByDeviceId(deviceId);
DeviceInfo deviceInfo = deviceCache.get(deviceId);
Product product = productCache.findById(deviceInfo.getProductKey());
return SpaceDeviceVo.builder()
.id(id)
@ -211,7 +211,6 @@ public class SpaceController {
.name(name == null ? product.getName() : name)
.homeId(space.getHomeId())
.spaceId(space.getId())
.spaceName(space.getName())
.build());
}

View File

@ -1,47 +0,0 @@
package cc.iotkit.manager.controller.mp;
import cc.iotkit.dao.UserInfoRepository;
import cc.iotkit.manager.model.vo.LoginResult;
import cc.iotkit.manager.service.WeChatService;
import cc.iotkit.manager.utils.AuthUtil;
import cc.iotkit.model.UserInfo;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController("mp-sys")
@RequestMapping("/mp/sys")
public class SystemController {
@Autowired
private WeChatService weChatService;
@Autowired
private UserInfoRepository userInfoRepository;
@ApiOperation("用户登录")
@ApiImplicitParams({
@ApiImplicitParam(value = "加密的用户信息", name = "userInfo", required = true, dataType = "String"),
@ApiImplicitParam(value = "加密向量", name = "iv", required = true, dataType = "String"),
@ApiImplicitParam(value = "登录码", name = "loginCode", required = true, dataType = "String"),
})
@PostMapping("/login")
public LoginResult login(String userInfo, String iv, String loginCode) {
return new LoginResult(weChatService.login(userInfo, iv, loginCode));
}
@ApiOperation("用户设置")
@ApiImplicitParams({
@ApiImplicitParam(value = "地址", name = "address", required = true, dataType = "String"),
})
@PostMapping("/settings")
public void settings(String address) {
UserInfo userInfo = userInfoRepository.findById(AuthUtil.getUserId()).get();
userInfo.setAddress(address);
userInfoRepository.save(userInfo);
}
}

View File

@ -43,6 +43,11 @@ public class SpaceDeviceVo {
*/
private String picUrl;
/**
* ID
*/
private String spaceId;
/**
*
*/

View File

@ -33,14 +33,13 @@ public class SpaceDeviceService {
List<SpaceDevice> spaceDevices = spaceDeviceRepository.findAll(Example.of(device));
List<SpaceDeviceVo> spaceDeviceVos = new ArrayList<>();
spaceDevices.forEach(sd -> {
DeviceInfo deviceInfo = deviceCache.findByDeviceId(sd.getDeviceId());
DeviceInfo deviceInfo = deviceCache.get(sd.getDeviceId());
Product product = productCache.findById(deviceInfo.getProductKey());
spaceDeviceVos.add(SpaceDeviceVo.builder()
.uid(sd.getUid())
.deviceId(sd.getDeviceId())
.name(sd.getName())
.picUrl(product.getImg())
.spaceName(sd.getSpaceName())
.online(deviceInfo.getState().isOnline())
.property(deviceInfo.getProperty())
.productKey(deviceInfo.getProductKey())

View File

@ -1,5 +1,6 @@
package cc.iotkit.model.space;
import cc.iotkit.model.Owned;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
@ -12,7 +13,7 @@ import org.springframework.data.mongodb.core.mapping.Document;
@NoArgsConstructor
@AllArgsConstructor
@Document
public class Home {
public class Home implements Owned {
@Id
private String id;
@ -41,4 +42,9 @@ public class Home {
*
*/
private Integer deviceNum;
/**
* 使
*/
private Boolean current;
}

View File

@ -1,5 +1,6 @@
package cc.iotkit.model.space;
import cc.iotkit.model.Owned;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
@ -12,7 +13,7 @@ import org.springframework.data.mongodb.core.mapping.Document;
@NoArgsConstructor
@AllArgsConstructor
@Document
public class Space {
public class Space implements Owned {
@Id
private String id;
@ -36,4 +37,6 @@ public class Space {
*
*/
private Integer deviceNum;
private Long createAt;
}

View File

@ -48,7 +48,13 @@ public class SpaceDevice {
private String spaceId;
/**
*
*
*/
private String spaceName;
private Long addAt;
/**
* 使
*/
private Long useAt;
}

View File

@ -43,7 +43,7 @@ public class DeviceBehaviourService {
private ServerConfig serverConfig;
@Autowired
private DeviceCache deviceCache;
@Autowired
// @Autowired
private DeviceStateHolder deviceStateHolder;
private Producer<ThingModelMessage> deviceMessageProducer;
@ -209,11 +209,11 @@ public class DeviceBehaviourService {
if (online) {
device.getState().setOnline(true);
device.getState().setOnlineTime(System.currentTimeMillis());
deviceStateHolder.online(device.getDeviceId());
// deviceStateHolder.online(device.getDeviceId());
} else {
device.getState().setOnline(false);
device.getState().setOfflineTime(System.currentTimeMillis());
deviceStateHolder.offline(device.getDeviceId());
// deviceStateHolder.offline(device.getDeviceId());
}
deviceRepository.save(device);

View File

@ -24,7 +24,7 @@ import java.util.concurrent.TimeUnit;
* 1
*/
@Slf4j
@Service
//@Service
public class DeviceStateHolder implements MessageListener<DeviceStateHolder.OfflineMessage> {
private ScheduledThreadPoolExecutor stateHolderTask;

View File

@ -38,7 +38,7 @@ public class DeviceCondition {
String[] pkDn = device.split("/");
if (pkDn.length < 2) {
//用deviceId取
deviceInfo = deviceCache.findByDeviceId(device);
deviceInfo = deviceCache.get(device);
} else {
//用pk/dn取
deviceInfo = deviceCache.getDeviceInfo(pkDn[0], pkDn[1]);