This commit is contained in:
kerwincui
2024-03-17 14:59:23 +08:00
parent 3d44f4674c
commit 5539c1b6af
999 changed files with 115642 additions and 10757 deletions

View File

@@ -0,0 +1,25 @@
package com.fastbee.data.controller;
import com.fastbee.common.core.controller.BaseController;
import org.springframework.web.bind.annotation.*;
/**
* 设备告警Controller
*
* @author kerwincui
* @date 2022-01-13
*/
@RestController
@RequestMapping("/oauth/resource")
public class AuthResourceController extends BaseController
{
/**
* 查询设备告警列表
*/
@GetMapping("/product")
public String findAll() {
return "查询产品列表成功!";
}
}

View File

@@ -0,0 +1,128 @@
package com.fastbee.data.controller;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import com.fastbee.common.core.domain.entity.SysRole;
import com.fastbee.common.core.domain.entity.SysUser;
import com.fastbee.common.core.page.TableDataInfo;
import com.fastbee.iot.model.IdAndName;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fastbee.common.annotation.Log;
import com.fastbee.common.core.controller.BaseController;
import com.fastbee.common.core.domain.AjaxResult;
import com.fastbee.common.enums.BusinessType;
import com.fastbee.iot.domain.Category;
import com.fastbee.iot.service.ICategoryService;
import com.fastbee.common.utils.poi.ExcelUtil;
/**
* 产品分类Controller
*
* @author kerwincui
* @date 2021-12-16
*/
@Api(tags = "产品分类")
@RestController
@RequestMapping("/iot/category")
public class CategoryController extends BaseController
{
@Autowired
private ICategoryService categoryService;
/**
* 查询产品分类列表
*/
@PreAuthorize("@ss.hasPermi('iot:category:list')")
@GetMapping("/list")
@ApiOperation("分类分页列表")
public TableDataInfo list(Category category)
{
startPage();
return getDataTable(categoryService.selectCategoryList(category));
}
/**
* 查询产品简短分类列表
*/
@PreAuthorize("@ss.hasPermi('iot:category:list')")
@GetMapping("/shortlist")
@ApiOperation("分类简短列表")
public AjaxResult shortlist()
{
return AjaxResult.success(categoryService.selectCategoryShortList());
}
/**
* 导出产品分类列表
*/
@PreAuthorize("@ss.hasPermi('iot:category:export')")
@Log(title = "产品分类", businessType = BusinessType.EXPORT)
@PostMapping("/export")
@ApiOperation("导出分类")
public void export(HttpServletResponse response, Category category)
{
List<Category> list = categoryService.selectCategoryList(category);
ExcelUtil<Category> util = new ExcelUtil<Category>(Category.class);
util.exportExcel(response, list, "产品分类数据");
}
/**
* 获取产品分类详细信息
*/
@ApiOperation("获取分类详情")
@PreAuthorize("@ss.hasPermi('iot:category:query')")
@GetMapping(value = "/{categoryId}")
public AjaxResult getInfo(@PathVariable("categoryId") Long categoryId)
{
return AjaxResult.success(categoryService.selectCategoryByCategoryId(categoryId));
}
/**
* 新增产品分类
*/
@PreAuthorize("@ss.hasPermi('iot:category:add')")
@Log(title = "产品分类", businessType = BusinessType.INSERT)
@PostMapping
@ApiOperation("添加分类")
public AjaxResult add(@RequestBody Category category)
{
return toAjax(categoryService.insertCategory(category));
}
/**
* 修改产品分类
*/
@PreAuthorize("@ss.hasPermi('iot:category:edit')")
@Log(title = "产品分类", businessType = BusinessType.UPDATE)
@PutMapping
@ApiOperation("修改分类")
public AjaxResult edit(@RequestBody Category category)
{
return toAjax(categoryService.updateCategory(category));
}
/**
* 删除产品分类
*/
@PreAuthorize("@ss.hasPermi('iot:category:remove')")
@Log(title = "产品分类", businessType = BusinessType.DELETE)
@DeleteMapping("/{categoryIds}")
@ApiOperation("批量删除分类")
public AjaxResult remove(@PathVariable Long[] categoryIds)
{
return categoryService.deleteCategoryByCategoryIds(categoryIds);
}
}

View File

@@ -0,0 +1,267 @@
package com.fastbee.data.controller;
import com.fastbee.common.annotation.Anonymous;
import com.fastbee.common.annotation.Log;
import com.fastbee.common.core.controller.BaseController;
import com.fastbee.common.core.domain.AjaxResult;
import com.fastbee.common.core.page.TableDataInfo;
import com.fastbee.common.enums.BusinessType;
import com.fastbee.common.utils.gateway.mq.TopicsUtils;
import com.fastbee.common.utils.poi.ExcelUtil;
import com.fastbee.iot.domain.Device;
import com.fastbee.iot.model.DeviceRelateUserInput;
import com.fastbee.iot.service.IDeviceService;
import com.fastbee.mq.service.IMqttMessagePublish;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
* 设备Controller
*
* @author kerwincui
* @date 2021-12-16
*/
@Api(tags = "设备管理")
@RestController
@RequestMapping("/iot/device")
public class DeviceController extends BaseController
{
@Autowired
private IDeviceService deviceService;
// @Lazy
@Autowired
private IMqttMessagePublish messagePublish;
/**
* 查询设备列表
*/
@PreAuthorize("@ss.hasPermi('iot:device:list')")
@GetMapping("/list")
@ApiOperation("设备分页列表")
public TableDataInfo list(Device device)
{
startPage();
return getDataTable(deviceService.selectDeviceList(device));
}
/**
* 查询未分配授权码设备列表
*/
@PreAuthorize("@ss.hasPermi('iot:device:list')")
@GetMapping("/unAuthlist")
@ApiOperation("设备分页列表")
public TableDataInfo unAuthlist(Device device)
{
startPage();
return getDataTable(deviceService.selectUnAuthDeviceList(device));
}
/**
* 查询分组可添加设备
*/
@PreAuthorize("@ss.hasPermi('iot:device:list')")
@GetMapping("/listByGroup")
@ApiOperation("查询分组可添加设备分页列表")
public TableDataInfo listByGroup(Device device)
{
startPage();
return getDataTable(deviceService.selectDeviceListByGroup(device));
}
/**
* 查询设备简短列表,主页列表数据
*/
@PreAuthorize("@ss.hasPermi('iot:device:list')")
@GetMapping("/shortList")
@ApiOperation("设备分页简短列表")
public TableDataInfo shortList(Device device)
{
startPage();
return getDataTable(deviceService.selectDeviceShortList(device));
}
/**
* 查询所有设备简短列表
*/
@PreAuthorize("@ss.hasPermi('iot:device:list')")
@GetMapping("/all")
@ApiOperation("查询所有设备简短列表")
public TableDataInfo allShortList()
{
return getDataTable(deviceService.selectAllDeviceShortList());
}
/**
* 导出设备列表
*/
@PreAuthorize("@ss.hasPermi('iot:device:export')")
@Log(title = "设备", businessType = BusinessType.EXPORT)
@PostMapping("/export")
@ApiOperation("导出设备")
public void export(HttpServletResponse response, Device device)
{
List<Device> list = deviceService.selectDeviceList(device);
ExcelUtil<Device> util = new ExcelUtil<Device>(Device.class);
util.exportExcel(response, list, "设备数据");
}
/**
* 获取设备详细信息
*/
@PreAuthorize("@ss.hasPermi('iot:device:query')")
@GetMapping(value = "/{deviceId}")
@ApiOperation("获取设备详情")
public AjaxResult getInfo(@PathVariable("deviceId") Long deviceId)
{
return AjaxResult.success(deviceService.selectDeviceByDeviceId(deviceId));
}
/**
* 设备数据同步
*/
@PreAuthorize("@ss.hasPermi('iot:device:query')")
@GetMapping(value = "/synchronization/{serialNumber}")
@ApiOperation("设备数据同步")
public AjaxResult deviceSynchronization(@PathVariable("serialNumber") String serialNumber)
{
return AjaxResult.success(messagePublish.deviceSynchronization(serialNumber));
}
/**
* 根据设备编号详细信息
*/
@PreAuthorize("@ss.hasPermi('iot:device:query')")
@GetMapping(value = "/getDeviceBySerialNumber/{serialNumber}")
@ApiOperation("根据设备编号获取设备详情")
public AjaxResult getInfoBySerialNumber(@PathVariable("serialNumber") String serialNumber)
{
return AjaxResult.success(deviceService.selectDeviceBySerialNumber(serialNumber));
}
/**
* 获取设备统计信息
*/
@PreAuthorize("@ss.hasPermi('iot:device:query')")
@GetMapping(value = "/statistic")
@ApiOperation("获取设备统计信息")
public AjaxResult getDeviceStatistic()
{
return AjaxResult.success(deviceService.selectDeviceStatistic());
}
/**
* 获取设备详细信息
*/
@PreAuthorize("@ss.hasPermi('iot:device:query')")
@GetMapping(value = "/runningStatus")
@ApiOperation("获取设备详情和运行状态")
public AjaxResult getRunningStatusInfo(Long deviceId, Integer slaveId)
{
return AjaxResult.success(deviceService.selectDeviceRunningStatusByDeviceId(deviceId,slaveId));
}
/**
* 新增设备
*/
@PreAuthorize("@ss.hasPermi('iot:device:add')")
@Log(title = "添加设备", businessType = BusinessType.INSERT)
@PostMapping
@ApiOperation("添加设备")
public AjaxResult add(@RequestBody Device device)
{
return AjaxResult.success(deviceService.insertDevice(device));
}
/**
* 设备关联用户
*/
@PreAuthorize("@ss.hasPermi('iot:device:add')")
@Log(title = "设备关联用户", businessType = BusinessType.UPDATE)
@PostMapping("/relateUser")
@ApiOperation("设备关联用户")
public AjaxResult relateUser(@RequestBody DeviceRelateUserInput deviceRelateUserInput)
{
if(deviceRelateUserInput.getUserId()==0 || deviceRelateUserInput.getUserId()==null){
return AjaxResult.error("用户ID不能为空");
}
if(deviceRelateUserInput.getDeviceNumberAndProductIds()==null || deviceRelateUserInput.getDeviceNumberAndProductIds().size()==0){
return AjaxResult.error("设备编号和产品ID不能为空");
}
return deviceService.deviceRelateUser(deviceRelateUserInput);
}
/**
* 修改设备
*/
@PreAuthorize("@ss.hasPermi('iot:device:edit')")
@Log(title = "修改设备", businessType = BusinessType.UPDATE)
@PutMapping
@ApiOperation("修改设备")
public AjaxResult edit(@RequestBody Device device)
{
return deviceService.updateDevice(device);
}
/**
* 重置设备状态
*/
@PreAuthorize("@ss.hasPermi('iot:device:edit')")
@Log(title = "重置设备状态", businessType = BusinessType.UPDATE)
@PutMapping("/reset/{serialNumber}")
@ApiOperation("重置设备状态")
public AjaxResult resetDeviceStatus(@PathVariable String serialNumber)
{
Device device=new Device();
device.setSerialNumber(serialNumber);
return toAjax(deviceService.resetDeviceStatus(device.getSerialNumber()));
}
/**
* 删除设备
*/
@PreAuthorize("@ss.hasPermi('iot:device:remove')")
@Log(title = "删除设备", businessType = BusinessType.DELETE)
@DeleteMapping("/{deviceIds}")
@ApiOperation("批量删除设备")
public AjaxResult remove(@PathVariable Long[] deviceIds) throws SchedulerException {
return toAjax(deviceService.deleteDeviceByDeviceId(deviceIds[0]));
}
/**
* 生成设备编号
*/
@PreAuthorize("@ss.hasPermi('iot:device:edit')")
@GetMapping("/generator")
@ApiOperation("生成设备编号")
public AjaxResult generatorDeviceNum(Integer type){
return AjaxResult.success("操作成功",deviceService.generationDeviceNum(type));
}
@PreAuthorize("@ss.hasPermi('iot:device:query')")
@GetMapping("/gwDevCount")
@ApiOperation("子设备数量")
public AjaxResult getGwDevCount(String gwDevCode){
return AjaxResult.success(deviceService.getSubDeviceCount(gwDevCode));
}
/**
* 获取设备MQTT连接参数
* @param deviceId 设备主键id
* @return
*/
@PreAuthorize("@ss.hasPermi('iot:device:query')")
@GetMapping("/getMqttConnectData")
@ApiOperation("获取设备MQTT连接参数")
public AjaxResult getMqttConnectData(Long deviceId){
return AjaxResult.success(deviceService.getMqttConnectData(deviceId));
}
}

View File

@@ -0,0 +1,147 @@
package com.fastbee.data.controller;
import com.fastbee.common.annotation.Log;
import com.fastbee.common.core.controller.BaseController;
import com.fastbee.common.core.domain.AjaxResult;
import com.fastbee.common.core.page.TableDataInfo;
import com.fastbee.common.enums.BusinessType;
import com.fastbee.common.exception.job.TaskException;
import com.fastbee.common.utils.poi.ExcelUtil;
import com.fastbee.iot.domain.DeviceJob;
import com.fastbee.iot.service.IDeviceJobService;
import com.fastbee.quartz.util.CronUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
* 调度任务信息操作处理
*
* @author kerwincui
*/
@Api(tags = "调度任务信息操作处理模块")
@RestController
@RequestMapping("/iot/job")
public class DeviceJobController extends BaseController
{
@Autowired
private IDeviceJobService jobService;
/**
* 查询定时任务列表
*/
@ApiOperation("查询定时任务列表")
@PreAuthorize("@ss.hasPermi('iot:device:list')")
@GetMapping("/list")
public TableDataInfo list(DeviceJob deviceJob)
{
startPage();
List<DeviceJob> list = jobService.selectJobList(deviceJob);
return getDataTable(list);
}
/**
* 导出定时任务列表
*/
@ApiOperation("导出定时任务列表")
@PreAuthorize("@ss.hasPermi('iot:device:export')")
@Log(title = "定时任务", businessType = BusinessType.EXPORT)
@PostMapping("/export")
public void export(HttpServletResponse response, DeviceJob deviceJob)
{
List<DeviceJob> list = jobService.selectJobList(deviceJob);
ExcelUtil<DeviceJob> util = new ExcelUtil<DeviceJob>(DeviceJob.class);
util.exportExcel(response, list, "定时任务");
}
/**
* 获取定时任务详细信息
*/
@ApiOperation("获取定时任务详细信息")
@PreAuthorize("@ss.hasPermi('iot:device:query')")
@GetMapping(value = "/{jobId}")
public AjaxResult getInfo(@PathVariable("jobId") Long jobId)
{
return AjaxResult.success(jobService.selectJobById(jobId));
}
/**
* 新增定时任务
*/
@ApiOperation("新增定时任务")
@PreAuthorize("@ss.hasPermi('iot:device:add')")
@Log(title = "定时任务", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@RequestBody DeviceJob job) throws SchedulerException, TaskException
{
if (!CronUtils.isValid(job.getCronExpression()))
{
return error("新增任务'" + job.getJobName() + "'失败Cron表达式不正确");
}
job.setCreateBy(getUsername());
return toAjax(jobService.insertJob(job));
}
/**
* 修改定时任务
*/
@ApiOperation("修改定时任务")
@PreAuthorize("@ss.hasPermi('iot:device:edit')")
@Log(title = "定时任务", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@RequestBody DeviceJob job) throws SchedulerException, TaskException
{
if (!CronUtils.isValid(job.getCronExpression()))
{
return error("修改任务'" + job.getJobName() + "'失败Cron表达式不正确");
}
job.setUpdateBy(getUsername());
return toAjax(jobService.updateJob(job));
}
/**
* 定时任务状态修改
*/
@ApiOperation("定时任务状态修改")
@PreAuthorize("@ss.hasPermi('iot:device:edit')")
@Log(title = "定时任务", businessType = BusinessType.UPDATE)
@PutMapping("/changeStatus")
public AjaxResult changeStatus(@RequestBody DeviceJob job) throws SchedulerException
{
DeviceJob newJob = jobService.selectJobById(job.getJobId());
newJob.setStatus(job.getStatus());
return toAjax(jobService.changeStatus(newJob));
}
/**
* 定时任务立即执行一次
*/
@ApiOperation("定时任务立即执行一次")
@PreAuthorize("@ss.hasPermi('iot:device:edit')")
@Log(title = "定时任务", businessType = BusinessType.UPDATE)
@PutMapping("/run")
public AjaxResult run(@RequestBody DeviceJob job) throws SchedulerException
{
jobService.run(job);
return AjaxResult.success();
}
/**
* 删除定时任务
*/
@ApiOperation("删除定时任务")
@PreAuthorize("@ss.hasPermi('iot:device:remove')")
@Log(title = "定时任务", businessType = BusinessType.DELETE)
@DeleteMapping("/{jobIds}")
public AjaxResult remove(@PathVariable Long[] jobIds) throws SchedulerException, TaskException
{
jobService.deleteJobByIds(jobIds);
return AjaxResult.success();
}
}

View File

@@ -0,0 +1,49 @@
package com.fastbee.data.controller;
import com.fastbee.common.annotation.Log;
import com.fastbee.common.core.controller.BaseController;
import com.fastbee.common.core.domain.AjaxResult;
import com.fastbee.common.core.page.TableDataInfo;
import com.fastbee.common.enums.BusinessType;
import com.fastbee.common.utils.poi.ExcelUtil;
import com.fastbee.iot.domain.DeviceLog;
import com.fastbee.iot.model.HistoryModel;
import com.fastbee.iot.model.MonitorModel;
import com.fastbee.iot.service.IDeviceLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
/**
* 设备日志Controller
*
* @author kerwincui
* @date 2022-01-13
*/
@Api(tags = "设备日志模块")
@RestController
@RequestMapping("/iot/deviceLog")
public class DeviceLogController extends BaseController
{
@Autowired
private IDeviceLogService deviceLogService;
/**
* 查询设备的监测数据
*/
@ApiOperation("查询设备的监测数据")
@PreAuthorize("@ss.hasPermi('iot:device:list')")
@GetMapping("/monitor")
public TableDataInfo monitorList(DeviceLog deviceLog)
{
List<MonitorModel> list = deviceLogService.selectMonitorList(deviceLog);
return getDataTable(list);
}
}

View File

@@ -0,0 +1,136 @@
package com.fastbee.data.controller;
import java.util.List;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fastbee.common.annotation.Log;
import com.fastbee.common.core.controller.BaseController;
import com.fastbee.common.core.domain.AjaxResult;
import com.fastbee.common.enums.BusinessType;
import com.fastbee.iot.domain.DeviceUser;
import com.fastbee.iot.service.IDeviceUserService;
import com.fastbee.common.core.page.TableDataInfo;
/**
* 设备用户Controller
*
* @author kerwincui
* @date 2021-12-16
*/
@Api(tags = "设备用户")
@RestController
@RequestMapping("/iot/deviceUser")
public class DeviceUserController extends BaseController
{
@Autowired
private IDeviceUserService deviceUserService;
/**
* 查询设备用户列表
*/
@PreAuthorize("@ss.hasPermi('iot:device:list')")
@GetMapping("/list")
@ApiOperation("设备用户分页列表")
public TableDataInfo list(DeviceUser deviceUser)
{
startPage();
List<DeviceUser> list = deviceUserService.selectDeviceUserList(deviceUser);
return getDataTable(list);
}
/**
* 获取设备分享用户信息
*/
@GetMapping("/shareUser")
public AjaxResult userList(DeviceUser user)
{
return AjaxResult.success(deviceUserService.selectShareUser(user));
}
/**
* 获取设备用户详细信息 根据deviceId 查询的话可能会查出多个
*/
@PreAuthorize("@ss.hasPermi('iot:device:query')")
@GetMapping(value = "/{deviceId}")
@ApiOperation("获取设备用户详情")
public AjaxResult getInfo(@PathVariable("deviceId") Long deviceId)
{
return AjaxResult.success(deviceUserService.selectDeviceUserByDeviceId(deviceId));
}
/**
* 获取设备用户详细信息 双主键 device_id 和 user_id
*/
@PreAuthorize("@ss.hasPermi('iot:device:query')")
@GetMapping(value = "/{deviceId}/{userId}")
@ApiOperation("获取设备用户详情,根据用户id 和 设备id")
public AjaxResult getInfo(@PathVariable("deviceId") Long deviceId, @PathVariable("userId") Long userId)
{
return AjaxResult.success(deviceUserService.selectDeviceUserByDeviceIdAndUserId(deviceId, userId));
}
/**
* 新增设备用户
*/
@PreAuthorize("@ss.hasPermi('iot:device:share')")
@Log(title = "设备用户", businessType = BusinessType.INSERT)
@PostMapping
@ApiOperation("添加设备用户")
public AjaxResult add(@RequestBody DeviceUser deviceUser)
{
return toAjax(deviceUserService.insertDeviceUser(deviceUser));
}
/**
* 新增多个设备用户
*/
@PreAuthorize("@ss.hasPermi('iot:device:share')")
@Log(title = "设备用户", businessType = BusinessType.INSERT)
@PostMapping("/addDeviceUsers")
@ApiOperation("批量添加设备用户")
public AjaxResult addDeviceUsers(@RequestBody List<DeviceUser> deviceUsers)
{
return toAjax(deviceUserService.insertDeviceUserList(deviceUsers));
}
/**
* 修改设备用户
*/
@ApiOperation("修改设备用户")
@PreAuthorize("@ss.hasPermi('iot:device:edit')")
@Log(title = "设备用户", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@RequestBody DeviceUser deviceUser)
{
return toAjax(deviceUserService.updateDeviceUser(deviceUser));
}
/**
* 删除设备用户
*/
@ApiOperation("删除设备用户")
@PreAuthorize("@ss.hasPermi('iot:device:remove')")
@Log(title = "设备用户", businessType = BusinessType.DELETE)
@DeleteMapping
public AjaxResult remove(@RequestBody DeviceUser deviceUser)
{
int count=deviceUserService.deleteDeviceUser(deviceUser);
if(count==0){
return AjaxResult.error("设备所有者不能删除");
}else{
return AjaxResult.success();
}
}
}

View File

@@ -0,0 +1,114 @@
package com.fastbee.data.controller;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import com.fastbee.iot.domain.EventLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fastbee.common.annotation.Log;
import com.fastbee.common.core.controller.BaseController;
import com.fastbee.common.core.domain.AjaxResult;
import com.fastbee.common.enums.BusinessType;
import com.fastbee.iot.service.IEventLogService;
import com.fastbee.common.utils.poi.ExcelUtil;
import com.fastbee.common.core.page.TableDataInfo;
/**
* 事件日志Controller
*
* @author kerwincui
* @date 2023-03-28
*/
@Api(tags = "事件日志")
@RestController
@RequestMapping("/iot/event")
public class EventLogController extends BaseController
{
@Autowired
private IEventLogService eventLogService;
/**
* 查询事件日志列表
*/
@ApiOperation("查询事件日志列表")
@PreAuthorize("@ss.hasPermi('iot:event:list')")
@GetMapping("/list")
public TableDataInfo list(EventLog eventLog)
{
startPage();
List<EventLog> list = eventLogService.selectEventLogList(eventLog);
return getDataTable(list);
}
/**
* 导出事件日志列表
*/
@ApiOperation("导出事件日志列表")
@PreAuthorize("@ss.hasPermi('iot:event:export')")
@Log(title = "事件日志", businessType = BusinessType.EXPORT)
@PostMapping("/export")
public void export(HttpServletResponse response, EventLog eventLog)
{
List<EventLog> list = eventLogService.selectEventLogList(eventLog);
ExcelUtil<EventLog> util = new ExcelUtil<EventLog>(EventLog.class);
util.exportExcel(response, list, "事件日志数据");
}
/**
* 获取事件日志详细信息
*/
@ApiOperation("获取事件日志详细信息")
@PreAuthorize("@ss.hasPermi('iot:event:query')")
@GetMapping(value = "/{logId}")
public AjaxResult getInfo(@PathVariable("logId") Long logId)
{
return success(eventLogService.selectEventLogByLogId(logId));
}
/**
* 新增事件日志
*/
@ApiOperation("新增事件日志")
@PreAuthorize("@ss.hasPermi('iot:event:add')")
@Log(title = "事件日志", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@RequestBody EventLog eventLog)
{
return toAjax(eventLogService.insertEventLog(eventLog));
}
/**
* 修改事件日志
*/
@ApiOperation("修改事件日志")
@PreAuthorize("@ss.hasPermi('iot:event:edit')")
@Log(title = "事件日志", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@RequestBody EventLog eventLog)
{
return toAjax(eventLogService.updateEventLog(eventLog));
}
/**
* 删除事件日志
*/
@ApiOperation("删除事件日志")
@PreAuthorize("@ss.hasPermi('iot:event:remove')")
@Log(title = "事件日志", businessType = BusinessType.DELETE)
@DeleteMapping("/{logIds}")
public AjaxResult remove(@PathVariable Long[] logIds)
{
return toAjax(eventLogService.deleteEventLogByLogIds(logIds));
}
}

View File

@@ -0,0 +1,114 @@
package com.fastbee.data.controller;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fastbee.common.annotation.Log;
import com.fastbee.common.core.controller.BaseController;
import com.fastbee.common.core.domain.AjaxResult;
import com.fastbee.common.enums.BusinessType;
import com.fastbee.iot.domain.FunctionLog;
import com.fastbee.iot.service.IFunctionLogService;
import com.fastbee.common.utils.poi.ExcelUtil;
import com.fastbee.common.core.page.TableDataInfo;
/**
* 设备服务下发日志Controller
*
* @author kerwincui
* @date 2022-10-22
*/
@Api(tags = "设备服务下发日志")
@RestController
@RequestMapping("/iot/log")
public class FunctionLogController extends BaseController
{
@Autowired
private IFunctionLogService functionLogService;
/**
* 查询设备服务下发日志列表
*/
@ApiOperation("查询设备服务下发日志列表")
@PreAuthorize("@ss.hasPermi('iot:log:list')")
@GetMapping("/list")
public TableDataInfo list(FunctionLog functionLog)
{
startPage();
List<FunctionLog> list = functionLogService.selectFunctionLogList(functionLog);
return getDataTable(list);
}
/**
* 导出设备服务下发日志列表
*/
@ApiOperation("导出设备服务下发日志列表")
@PreAuthorize("@ss.hasPermi('iot:log:export')")
@Log(title = "设备服务下发日志", businessType = BusinessType.EXPORT)
@PostMapping("/export")
public void export(HttpServletResponse response, FunctionLog functionLog)
{
List<FunctionLog> list = functionLogService.selectFunctionLogList(functionLog);
ExcelUtil<FunctionLog> util = new ExcelUtil<FunctionLog>(FunctionLog.class);
util.exportExcel(response, list, "设备服务下发日志数据");
}
/**
* 获取设备服务下发日志详细信息
*/
@ApiOperation("获取设备服务下发日志详细信息")
@PreAuthorize("@ss.hasPermi('iot:log:query')")
@GetMapping(value = "/{id}")
public AjaxResult getInfo(@PathVariable("id") Long id)
{
return AjaxResult.success(functionLogService.selectFunctionLogById(id));
}
/**
* 新增设备服务下发日志
*/
@ApiOperation("新增设备服务下发日志")
@PreAuthorize("@ss.hasPermi('iot:log:add')")
@Log(title = "设备服务下发日志", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@RequestBody FunctionLog functionLog)
{
return toAjax(functionLogService.insertFunctionLog(functionLog));
}
/**
* 修改设备服务下发日志
*/
@ApiOperation("修改设备服务下发日志")
@PreAuthorize("@ss.hasPermi('iot:log:edit')")
@Log(title = "设备服务下发日志", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@RequestBody FunctionLog functionLog)
{
return toAjax(functionLogService.updateFunctionLog(functionLog));
}
/**
* 删除设备服务下发日志
*/
@ApiOperation("删除设备服务下发日志")
@PreAuthorize("@ss.hasPermi('iot:log:remove')")
@Log(title = "设备服务下发日志", businessType = BusinessType.DELETE)
@DeleteMapping("/{ids}")
public AjaxResult remove(@PathVariable Long[] ids)
{
return toAjax(functionLogService.deleteFunctionLogByIds(ids));
}
}

View File

@@ -0,0 +1,140 @@
package com.fastbee.data.controller;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import com.fastbee.iot.domain.DeviceGroup;
import com.fastbee.iot.model.DeviceGroupInput;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fastbee.common.annotation.Log;
import com.fastbee.common.core.controller.BaseController;
import com.fastbee.common.core.domain.AjaxResult;
import com.fastbee.common.enums.BusinessType;
import com.fastbee.iot.domain.Group;
import com.fastbee.iot.service.IGroupService;
import com.fastbee.common.utils.poi.ExcelUtil;
import com.fastbee.common.core.page.TableDataInfo;
/**
* 设备分组Controller
*
* @author kerwincui
* @date 2021-12-16
*/
@Api(tags = "设备分组")
@RestController
@RequestMapping("/iot/group")
public class GroupController extends BaseController
{
@Autowired
private IGroupService groupService;
/**
* 查询设备分组列表
*/
@PreAuthorize("@ss.hasPermi('iot:group:list')")
@GetMapping("/list")
@ApiOperation("分组分页列表")
public TableDataInfo list(Group group)
{
startPage();
return getDataTable(groupService.selectGroupList(group));
}
/**
* 导出设备分组列表
*/
@PreAuthorize("@ss.hasPermi('iot:group:export')")
@Log(title = "分组", businessType = BusinessType.EXPORT)
@PostMapping("/export")
@ApiOperation("导出分组")
public void export(HttpServletResponse response, Group group)
{
List<Group> list = groupService.selectGroupList(group);
ExcelUtil<Group> util = new ExcelUtil<Group>(Group.class);
util.exportExcel(response, list, "设备分组数据");
}
/**
* 获取设备分组详细信息
*/
@PreAuthorize("@ss.hasPermi('iot:group:query')")
@GetMapping(value = "/{groupId}")
@ApiOperation("获取分组详情")
public AjaxResult getInfo(@PathVariable("groupId") Long groupId)
{
return AjaxResult.success(groupService.selectGroupByGroupId(groupId));
}
/**
* 获取分组下的所有关联设备ID数组
*/
@PreAuthorize("@ss.hasPermi('iot:group:query')")
@GetMapping(value = "/getDeviceIds/{groupId}")
@ApiOperation("获取分组下的所有关联设备ID数组")
public AjaxResult getDeviceIds(@PathVariable("groupId") Long groupId)
{
return AjaxResult.success(groupService.selectDeviceIdsByGroupId(groupId));
}
/**
* 新增设备分组
*/
@PreAuthorize("@ss.hasPermi('iot:group:add')")
@Log(title = "分组", businessType = BusinessType.INSERT)
@PostMapping
@ApiOperation("添加分组")
public AjaxResult add(@RequestBody Group group)
{
return toAjax(groupService.insertGroup(group));
}
/**
* 更新分组下的关联设备
* @param input
* @return
*/
@PreAuthorize("@ss.hasPermi('iot:group:edit')")
@Log(title = "设备分组", businessType = BusinessType.UPDATE)
@PutMapping("/updateDeviceGroups")
@ApiOperation("更新分组下的关联设备")
public AjaxResult updateDeviceGroups(@RequestBody DeviceGroupInput input){
return toAjax(groupService.updateDeviceGroups(input));
}
/**
* 修改设备分组
*/
@PreAuthorize("@ss.hasPermi('iot:group:edit')")
@Log(title = "分组", businessType = BusinessType.UPDATE)
@PutMapping
@ApiOperation("修改分组")
public AjaxResult edit(@RequestBody Group group)
{
return toAjax(groupService.updateGroup(group));
}
/**
* 删除设备分组
*/
@PreAuthorize("@ss.hasPermi('iot:group:remove')")
@Log(title = "分组", businessType = BusinessType.DELETE)
@DeleteMapping("/{groupIds}")
@ApiOperation("批量删除设备分组")
public AjaxResult remove(@PathVariable Long[] groupIds)
{
return toAjax(groupService.deleteGroupByGroupIds(groupIds));
}
}

View File

@@ -0,0 +1,126 @@
package com.fastbee.data.controller;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import com.fastbee.iot.model.IdAndName;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fastbee.common.annotation.Log;
import com.fastbee.common.core.controller.BaseController;
import com.fastbee.common.core.domain.AjaxResult;
import com.fastbee.common.enums.BusinessType;
import com.fastbee.iot.domain.NewsCategory;
import com.fastbee.iot.service.INewsCategoryService;
import com.fastbee.common.utils.poi.ExcelUtil;
import com.fastbee.common.core.page.TableDataInfo;
/**
* 新闻分类Controller
*
* @author kerwincui
* @date 2022-04-09
*/
@Api(tags = "新闻分类")
@RestController
@RequestMapping("/iot/newsCategory")
public class NewsCategoryController extends BaseController
{
@Autowired
private INewsCategoryService newsCategoryService;
/**
* 查询新闻分类列表
*/
@PreAuthorize("@ss.hasPermi('iot:newsCategory:list')")
@GetMapping("/list")
@ApiOperation("新闻分类分页列表")
public TableDataInfo list(NewsCategory newsCategory)
{
startPage();
List<NewsCategory> list = newsCategoryService.selectNewsCategoryList(newsCategory);
return getDataTable(list);
}
/**
* 查询新闻分类简短列表
*/
@PreAuthorize("@ss.hasPermi('iot:news:list')")
@GetMapping("/newsCategoryShortList")
@ApiOperation("分类简短列表")
public AjaxResult newsCategoryShortList()
{
List<IdAndName> list = newsCategoryService.selectNewsCategoryShortList();
return AjaxResult.success(list);
}
/**
* 导出新闻分类列表
*/
@PreAuthorize("@ss.hasPermi('iot:newsCategory:export')")
@Log(title = "新闻分类", businessType = BusinessType.EXPORT)
@PostMapping("/export")
public void export(HttpServletResponse response, NewsCategory newsCategory)
{
List<NewsCategory> list = newsCategoryService.selectNewsCategoryList(newsCategory);
ExcelUtil<NewsCategory> util = new ExcelUtil<NewsCategory>(NewsCategory.class);
util.exportExcel(response, list, "新闻分类数据");
}
/**
* 获取新闻分类详细信息
*/
@PreAuthorize("@ss.hasPermi('iot:newsCategory:query')")
@GetMapping(value = "/{categoryId}")
@ApiOperation("新闻分类详情")
public AjaxResult getInfo(@PathVariable("categoryId") Long categoryId)
{
return AjaxResult.success(newsCategoryService.selectNewsCategoryByCategoryId(categoryId));
}
/**
* 新增新闻分类
*/
@PreAuthorize("@ss.hasPermi('iot:newsCategory:add')")
@Log(title = "新闻分类", businessType = BusinessType.INSERT)
@PostMapping
@ApiOperation("添加新闻分类")
public AjaxResult add(@RequestBody NewsCategory newsCategory)
{
return toAjax(newsCategoryService.insertNewsCategory(newsCategory));
}
/**
* 修改新闻分类
*/
@PreAuthorize("@ss.hasPermi('iot:newsCategory:edit')")
@Log(title = "新闻分类", businessType = BusinessType.UPDATE)
@PutMapping
@ApiOperation("修改新闻分类")
public AjaxResult edit(@RequestBody NewsCategory newsCategory)
{
return toAjax(newsCategoryService.updateNewsCategory(newsCategory));
}
/**
* 删除新闻分类
*/
@PreAuthorize("@ss.hasPermi('iot:newsCategory:remove')")
@Log(title = "新闻分类", businessType = BusinessType.DELETE)
@DeleteMapping("/{categoryIds}")
@ApiOperation("删除新闻分类")
public AjaxResult remove(@PathVariable Long[] categoryIds)
{
return newsCategoryService.deleteNewsCategoryByCategoryIds(categoryIds);
}
}

View File

@@ -0,0 +1,141 @@
package com.fastbee.data.controller;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import com.fastbee.iot.model.CategoryNews;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fastbee.common.annotation.Log;
import com.fastbee.common.core.controller.BaseController;
import com.fastbee.common.core.domain.AjaxResult;
import com.fastbee.common.enums.BusinessType;
import com.fastbee.iot.domain.News;
import com.fastbee.iot.service.INewsService;
import com.fastbee.common.utils.poi.ExcelUtil;
import com.fastbee.common.core.page.TableDataInfo;
/**
* 新闻资讯Controller
*
* @author kerwincui
* @date 2022-04-09
*/
@Api(tags = "新闻资讯")
@RestController
@RequestMapping("/iot/news")
public class NewsController extends BaseController
{
@Autowired
private INewsService newsService;
/**
* 查询新闻资讯列表
*/
@PreAuthorize("@ss.hasPermi('iot:news:list')")
@GetMapping("/list")
@ApiOperation("新闻分页列表")
public TableDataInfo list(News news)
{
startPage();
List<News> list = newsService.selectNewsList(news);
return getDataTable(list);
}
/**
* 查询轮播的新闻资讯
*/
@PreAuthorize("@ss.hasPermi('iot:news:list')")
@GetMapping("/bannerList")
@ApiOperation("轮播新闻列表")
public AjaxResult bannerList()
{
News news=new News();
news.setIsBanner(1);
news.setStatus(1);
List<News> list = newsService.selectNewsList(news);
return AjaxResult.success(list);
}
/**
* 查询置顶的新闻资讯
*/
@PreAuthorize("@ss.hasPermi('iot:news:list')")
@GetMapping("/topList")
@ApiOperation("置顶新闻列表")
public AjaxResult topList()
{
List<CategoryNews> list = newsService.selectTopNewsList();
return AjaxResult.success(list);
}
/**
* 导出新闻资讯列表
*/
@PreAuthorize("@ss.hasPermi('iot:news:export')")
@Log(title = "新闻资讯", businessType = BusinessType.EXPORT)
@PostMapping("/export")
public void export(HttpServletResponse response, News news)
{
List<News> list = newsService.selectNewsList(news);
ExcelUtil<News> util = new ExcelUtil<News>(News.class);
util.exportExcel(response, list, "新闻资讯数据");
}
/**
* 获取新闻资讯详细信息
*/
@PreAuthorize("@ss.hasPermi('iot:news:query')")
@GetMapping(value = "/{newsId}")
@ApiOperation("新闻详情")
public AjaxResult getInfo(@PathVariable("newsId") Long newsId)
{
return AjaxResult.success(newsService.selectNewsByNewsId(newsId));
}
/**
* 新增新闻资讯
*/
@PreAuthorize("@ss.hasPermi('iot:news:add')")
@Log(title = "新闻资讯", businessType = BusinessType.INSERT)
@PostMapping
@ApiOperation("添加新闻资讯")
public AjaxResult add(@RequestBody News news)
{
return toAjax(newsService.insertNews(news));
}
/**
* 修改新闻资讯
*/
@PreAuthorize("@ss.hasPermi('iot:news:edit')")
@Log(title = "新闻资讯", businessType = BusinessType.UPDATE)
@PutMapping
@ApiOperation("修改新闻资讯")
public AjaxResult edit(@RequestBody News news)
{
return toAjax(newsService.updateNews(news));
}
/**
* 删除新闻资讯
*/
@PreAuthorize("@ss.hasPermi('iot:news:remove')")
@Log(title = "新闻资讯", businessType = BusinessType.DELETE)
@DeleteMapping("/{newsIds}")
@ApiOperation("删除新闻资讯")
public AjaxResult remove(@PathVariable Long[] newsIds)
{
return toAjax(newsService.deleteNewsByNewsIds(newsIds));
}
}

View File

@@ -0,0 +1,114 @@
package com.fastbee.data.controller;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fastbee.common.annotation.Log;
import com.fastbee.common.core.controller.BaseController;
import com.fastbee.common.core.domain.AjaxResult;
import com.fastbee.common.enums.BusinessType;
import com.fastbee.iot.domain.OauthClientDetails;
import com.fastbee.iot.service.IOauthClientDetailsService;
import com.fastbee.common.utils.poi.ExcelUtil;
import com.fastbee.common.core.page.TableDataInfo;
/**
* 云云对接Controller
*
* @author kerwincui
* @date 2022-02-07
*/
@Api(tags = "云云对接")
@RestController
@RequestMapping("/iot/clientDetails")
public class OauthClientDetailsController extends BaseController
{
@Autowired
private IOauthClientDetailsService oauthClientDetailsService;
/**
* 查询云云对接列表
*/
@ApiOperation("查询云云对接列表")
@PreAuthorize("@ss.hasPermi('iot:clientDetails:list')")
@GetMapping("/list")
public TableDataInfo list(OauthClientDetails oauthClientDetails)
{
startPage();
List<OauthClientDetails> list = oauthClientDetailsService.selectOauthClientDetailsList(oauthClientDetails);
return getDataTable(list);
}
/**
* 导出云云对接列表
*/
@ApiOperation("导出云云对接列表")
@PreAuthorize("@ss.hasPermi('iot:clientDetails:export')")
@Log(title = "云云对接", businessType = BusinessType.EXPORT)
@PostMapping("/export")
public void export(HttpServletResponse response, OauthClientDetails oauthClientDetails)
{
List<OauthClientDetails> list = oauthClientDetailsService.selectOauthClientDetailsList(oauthClientDetails);
ExcelUtil<OauthClientDetails> util = new ExcelUtil<OauthClientDetails>(OauthClientDetails.class);
util.exportExcel(response, list, "云云对接数据");
}
/**
* 获取云云对接详细信息
*/
@ApiOperation("获取云云对接详细信息")
@PreAuthorize("@ss.hasPermi('iot:clientDetails:query')")
@GetMapping(value = "/{clientId}")
public AjaxResult getInfo(@PathVariable("clientId") String clientId)
{
return AjaxResult.success(oauthClientDetailsService.selectOauthClientDetailsByClientId(clientId));
}
/**
* 新增云云对接
*/
@ApiOperation("新增云云对接")
@PreAuthorize("@ss.hasPermi('iot:clientDetails:add')")
@Log(title = "云云对接", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@RequestBody OauthClientDetails oauthClientDetails)
{
return toAjax(oauthClientDetailsService.insertOauthClientDetails(oauthClientDetails));
}
/**
* 修改云云对接
*/
@ApiOperation("修改云云对接")
@PreAuthorize("@ss.hasPermi('iot:clientDetails:edit')")
@Log(title = "云云对接", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@RequestBody OauthClientDetails oauthClientDetails)
{
return toAjax(oauthClientDetailsService.updateOauthClientDetails(oauthClientDetails));
}
/**
* 修改云云对接
*/
@ApiOperation("修改云云对接")
@PreAuthorize("@ss.hasPermi('iot:clientDetails:remove')")
@Log(title = "云云对接", businessType = BusinessType.DELETE)
@DeleteMapping("/{clientIds}")
public AjaxResult remove(@PathVariable String[] clientIds)
{
return toAjax(oauthClientDetailsService.deleteOauthClientDetailsByClientIds(clientIds));
}
}

View File

@@ -0,0 +1,121 @@
package com.fastbee.data.controller;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import com.fastbee.iot.model.ProductAuthorizeVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.fastbee.common.annotation.Log;
import com.fastbee.common.core.controller.BaseController;
import com.fastbee.common.core.domain.AjaxResult;
import com.fastbee.common.enums.BusinessType;
import com.fastbee.iot.domain.ProductAuthorize;
import com.fastbee.iot.service.IProductAuthorizeService;
import com.fastbee.common.utils.poi.ExcelUtil;
import com.fastbee.common.core.page.TableDataInfo;
/**
* 产品授权码Controller
*
* @author kami
* @date 2022-04-11
*/
@Api(tags = "产品授权码")
@RestController
@RequestMapping("/iot/authorize")
public class ProductAuthorizeController extends BaseController
{
@Autowired
private IProductAuthorizeService productAuthorizeService;
/**
* 查询产品授权码列表
*/
@ApiOperation("查询产品授权码列表")
@PreAuthorize("@ss.hasPermi('iot:product:list')")
@GetMapping("/list")
public TableDataInfo list(ProductAuthorize productAuthorize)
{
startPage();
List<ProductAuthorize> list = productAuthorizeService.selectProductAuthorizeList(productAuthorize);
return getDataTable(list);
}
/**
* 导出产品授权码列表
*/
@ApiOperation("导出产品授权码列表")
@PreAuthorize("@ss.hasPermi('iot:authorize:export')")
@Log(title = "产品授权码", businessType = BusinessType.EXPORT)
@PostMapping("/export")
public void export(HttpServletResponse response, ProductAuthorize productAuthorize)
{
List<ProductAuthorize> list = productAuthorizeService.selectProductAuthorizeList(productAuthorize);
ExcelUtil<ProductAuthorize> util = new ExcelUtil<ProductAuthorize>(ProductAuthorize.class);
util.exportExcel(response, list, "产品授权码数据");
}
/**
* 获取产品授权码详细信息
*/
@ApiOperation("获取产品授权码详细信息")
@PreAuthorize("@ss.hasPermi('iot:authorize:query')")
@GetMapping(value = "/{authorizeId}")
public AjaxResult getInfo(@PathVariable("authorizeId") Long authorizeId)
{
return AjaxResult.success(productAuthorizeService.selectProductAuthorizeByAuthorizeId(authorizeId));
}
/**
* 新增产品授权码
*/
@ApiOperation("新增产品授权码")
@PreAuthorize("@ss.hasPermi('iot:authorize:add')")
@Log(title = "产品授权码", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@RequestBody ProductAuthorize productAuthorize)
{
return toAjax(productAuthorizeService.insertProductAuthorize(productAuthorize));
}
/**
* 根据数量批量新增产品授权码
*/
@ApiOperation("根据数量批量新增产品授权码")
@PreAuthorize("@ss.hasPermi('iot:authorize:add')")
@Log(title = "根据数量批量新增产品授权码", businessType = BusinessType.INSERT)
@PostMapping("addProductAuthorizeByNum")
public AjaxResult addProductAuthorizeByNum(@RequestBody ProductAuthorizeVO productAuthorizeVO)
{
return toAjax(productAuthorizeService.addProductAuthorizeByNum(productAuthorizeVO));
}
/**
* 修改产品授权码
*/
@ApiOperation("修改产品授权码")
@PreAuthorize("@ss.hasPermi('iot:authorize:edit')")
@Log(title = "产品授权码", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@RequestBody ProductAuthorize productAuthorize)
{
return toAjax(productAuthorizeService.updateProductAuthorize(productAuthorize));
}
/**
* 删除产品授权码
*/
@ApiOperation("删除产品授权码")
@PreAuthorize("@ss.hasPermi('iot:authorize:remove')")
@Log(title = "产品授权码", businessType = BusinessType.DELETE)
@DeleteMapping("/{authorizeIds}")
public AjaxResult remove(@PathVariable Long[] authorizeIds)
{
return toAjax(productAuthorizeService.deleteProductAuthorizeByAuthorizeIds(authorizeIds));
}
}

View File

@@ -0,0 +1,154 @@
package com.fastbee.data.controller;
import com.fastbee.common.annotation.Log;
import com.fastbee.common.core.controller.BaseController;
import com.fastbee.common.core.domain.AjaxResult;
import com.fastbee.common.core.page.TableDataInfo;
import com.fastbee.common.enums.BusinessType;
import com.fastbee.common.utils.poi.ExcelUtil;
import com.fastbee.iot.domain.Product;
import com.fastbee.iot.model.ChangeProductStatusModel;
import com.fastbee.iot.model.IdAndName;
import com.fastbee.iot.service.IProductService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
* 产品Controller
*
* @author kerwincui
* @date 2021-12-16
*/
@Api(tags = "产品管理")
@RestController
@RequestMapping("/iot/product")
public class ProductController extends BaseController
{
@Autowired
private IProductService productService;
/**
* 查询产品列表
*/
@GetMapping("/list")
@ApiOperation("产品分页列表")
public TableDataInfo list(Product product)
{
startPage();
return getDataTable(productService.selectProductList(product));
}
/**
* 查询产品简短列表
*/
@PreAuthorize("@ss.hasPermi('iot:product:list')")
@GetMapping("/shortList")
@ApiOperation("产品简短列表")
public AjaxResult shortList(Product product)
{
List<IdAndName> list = productService.selectProductShortList();
return AjaxResult.success(list);
}
/**
* 导出产品列表
*/
@PreAuthorize("@ss.hasPermi('iot:product:export')")
@Log(title = "产品", businessType = BusinessType.EXPORT)
@PostMapping("/export")
@ApiOperation("导出产品")
public void export(HttpServletResponse response, Product product)
{
List<Product> list = productService.selectProductList(product);
ExcelUtil<Product> util = new ExcelUtil<Product>(Product.class);
util.exportExcel(response, list, "产品数据");
}
/**
* 获取产品详细信息
*/
@PreAuthorize("@ss.hasPermi('iot:product:query')")
@GetMapping(value = "/{productId}")
@ApiOperation("获取产品详情")
public AjaxResult getInfo(@PathVariable("productId") Long productId)
{
return AjaxResult.success(productService.selectProductByProductId(productId));
}
/**
* 新增产品
*/
@PreAuthorize("@ss.hasPermi('iot:product:add')")
@Log(title = "添加产品", businessType = BusinessType.INSERT)
@PostMapping
@ApiOperation("添加产品")
public AjaxResult add(@RequestBody Product product)
{
return AjaxResult.success(productService.insertProduct(product));
}
/**
* 修改产品
*/
@PreAuthorize("@ss.hasPermi('iot:product:edit')")
@Log(title = "修改产品", businessType = BusinessType.UPDATE)
@PutMapping
@ApiOperation("修改产品")
public AjaxResult edit(@RequestBody Product product)
{
return toAjax(productService.updateProduct(product));
}
/**
* 获取产品下面的设备数量
*/
@PreAuthorize("@ss.hasPermi('iot:product:query')")
@GetMapping("/deviceCount/{productId}")
@ApiOperation("获取产品下面的设备数量")
public AjaxResult deviceCount(@PathVariable Long productId)
{
return AjaxResult.success(productService.selectDeviceCountByProductId(productId));
}
/**
* 发布产品
*/
@PreAuthorize("@ss.hasPermi('iot:product:add')")
@Log(title = "更新产品状态", businessType = BusinessType.UPDATE)
@PutMapping("/status")
@ApiOperation("更新产品状态")
public AjaxResult changeProductStatus(@RequestBody ChangeProductStatusModel model)
{
return productService.changeProductStatus(model);
}
/**
* 删除产品
*/
@PreAuthorize("@ss.hasPermi('iot:product:remove')")
@Log(title = "产品", businessType = BusinessType.DELETE)
@DeleteMapping("/{productIds}")
@ApiOperation("批量删除产品")
public AjaxResult remove(@PathVariable Long[] productIds)
{
return productService.deleteProductByProductIds(productIds);
}
/**
* 查询采集点模板关联的所有产品
*/
@PreAuthorize("@ss.hasPermi('iot:product:list')")
@GetMapping("/queryByTemplateId")
@ApiOperation("查询采集点模板id关联的所有产品")
public AjaxResult queryByTemplateId(@RequestParam Long templateId){
return AjaxResult.success(productService.selectByTempleId(templateId));
}
}

View File

@@ -0,0 +1,104 @@
package com.fastbee.data.controller;
import com.fastbee.common.core.domain.AjaxResult;
import com.fastbee.common.core.domain.model.BindLoginBody;
import com.fastbee.common.core.domain.model.BindRegisterBody;
import com.fastbee.iot.service.ISocialLoginService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import me.zhyd.oauth.model.AuthCallback;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 第三方登录接口Controller
*
* @author json
* @date 2022-04-12
*/
@Api(tags = "第三方登录接口")
@RestController
@RequestMapping("/auth")
public class SocialLoginController {
@Autowired
private ISocialLoginService iSocialLoginService;
@GetMapping("/render/{source}")
@ApiOperation("微信登录跳转二维码")
@ApiImplicitParam(name = "source", value = "登录类型", required = true, dataType = "String", paramType = "path", dataTypeClass = String.class)
public void renderAuth(HttpServletResponse httpServletResponse, HttpServletRequest httpServletRequest, @PathVariable String source) throws IOException {
// 生成授权页面
httpServletResponse.sendRedirect(iSocialLoginService.renderAuth(source, httpServletRequest));
}
@GetMapping("/callback/{source}")
@ApiOperation("微信登录扫码回调api")
@ApiImplicitParam(name = "source", value = "平台来源", required = true, dataType = "String", paramType = "path", dataTypeClass = String.class)
public void login(@PathVariable("source") String source, AuthCallback authCallback, HttpServletResponse httpServletResponse, HttpServletRequest httpServletRequest) throws IOException {
//回调接口
httpServletResponse.sendRedirect(iSocialLoginService.callback(source, authCallback, httpServletRequest));
}
@GetMapping("/checkBindId/{bindId}")
@ApiOperation("检查bindId")
@ApiImplicitParam(name = "bindId", value = "绑定ID", required = true, dataType = "String", paramType = "path", dataTypeClass = String.class)
public AjaxResult checkBindId(@PathVariable String bindId) {
return iSocialLoginService.checkBindId(bindId);
}
@GetMapping("/getErrorMsg/{errorId}")
@ApiOperation("获取errorMsg")
@ApiImplicitParam(name = "errorId", value = "错误提示ID", required = true, dataType = "String", paramType = "path", dataTypeClass = String.class)
public AjaxResult getErrorMsg(@PathVariable String errorId) {
return iSocialLoginService.getErrorMsg(errorId);
}
/**
* 已经绑定账户,跳转登录接口
*
* @param loginId
* @return
*/
@GetMapping("/login/{loginId}")
@ApiOperation("跳转登录api")
@ApiImplicitParam(name = "loginId", value = "登录Id", required = true, dataType = "String", paramType = "path", dataTypeClass = String.class)
public AjaxResult socialLogin(@PathVariable String loginId) {
// 生成授权页面
return iSocialLoginService.socialLogin(loginId);
}
/**
* 登录方法
*
* @param bindLoginBody 绑定登录信息
* @return 结果
*/
@ApiOperation("绑定登录方法")
@PostMapping("/bind/login")
public AjaxResult bindLogin(@RequestBody BindLoginBody bindLoginBody) {
return iSocialLoginService.bindLogin(bindLoginBody);
}
/**
* 注册绑定接口
*
* @param bindRegisterBody 注册信息
* @return 注册绑定信息
*/
@ApiOperation("注册绑定")
@PostMapping("/bind/register")
public AjaxResult bindRegister(@RequestBody BindRegisterBody bindRegisterBody) {
return iSocialLoginService.bindRegister(bindRegisterBody);
}
}

View File

@@ -0,0 +1,109 @@
package com.fastbee.data.controller;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fastbee.common.annotation.Log;
import com.fastbee.common.core.controller.BaseController;
import com.fastbee.common.core.domain.AjaxResult;
import com.fastbee.common.enums.BusinessType;
import com.fastbee.iot.domain.SocialPlatform;
import com.fastbee.iot.service.ISocialPlatformService;
import com.fastbee.common.utils.poi.ExcelUtil;
import com.fastbee.common.core.page.TableDataInfo;
/**
* 第三方登录平台控制Controller
*
* @author kerwincui
* @date 2022-04-11
*/
@Api(tags = "第三方登录平台")
@RestController
@RequestMapping("/iot/platform")
public class SocialPlatformController extends BaseController {
@Autowired
private ISocialPlatformService socialPlatformService;
/**
* 查询第三方登录平台控制列表
*/
@PreAuthorize("@ss.hasPermi('iot:platform:list')")
@GetMapping("/list")
@ApiOperation("第三方登录平台分页列表")
public TableDataInfo list(SocialPlatform socialPlatform) {
startPage();
List<SocialPlatform> list = socialPlatformService.selectSocialPlatformList(socialPlatform);
return getDataTable(list);
}
/**
* 导出第三方登录平台控制列表
*/
@ApiOperation("导出第三方登录平台控制列表")
@PreAuthorize("@ss.hasPermi('iot:platform:export')")
@Log(title = "第三方登录平台控制", businessType = BusinessType.EXPORT)
@PostMapping("/export")
public void export(HttpServletResponse response, SocialPlatform socialPlatform) {
List<SocialPlatform> list = socialPlatformService.selectSocialPlatformList(socialPlatform);
ExcelUtil<SocialPlatform> util = new ExcelUtil<SocialPlatform>(SocialPlatform.class);
util.exportExcel(response, list, "第三方登录平台控制数据");
}
/**
* 获取第三方登录平台控制详细信息
*/
@ApiOperation("获取第三方登录平台控制详细信息")
@PreAuthorize("@ss.hasPermi('iot:platform:query')")
@GetMapping(value = "/{socialPlatformId}")
public AjaxResult getInfo(@PathVariable("socialPlatformId") Long socialPlatformId) {
return AjaxResult.success(socialPlatformService.selectSocialPlatformBySocialPlatformId(socialPlatformId));
}
/**
* 新增第三方登录平台控制
*/
@ApiOperation("新增第三方登录平台控制")
@PreAuthorize("@ss.hasPermi('iot:platform:add')")
@Log(title = "第三方登录平台控制", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@RequestBody SocialPlatform socialPlatform) {
socialPlatform.setCreateBy(getUsername());
return toAjax(socialPlatformService.insertSocialPlatform(socialPlatform));
}
/**
* 修改第三方登录平台控制
*/
@ApiOperation("修改第三方登录平台控制")
@PreAuthorize("@ss.hasPermi('iot:platform:edit')")
@Log(title = "第三方登录平台控制", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@RequestBody SocialPlatform socialPlatform) {
socialPlatform.setUpdateBy(getUsername());
return toAjax(socialPlatformService.updateSocialPlatform(socialPlatform));
}
/**
* 删除第三方登录平台控制
*/
@ApiOperation("删除第三方登录平台控制")
@PreAuthorize("@ss.hasPermi('iot:platform:remove')")
@Log(title = "第三方登录平台控制", businessType = BusinessType.DELETE)
@DeleteMapping("/{socialPlatformIds}")
public AjaxResult remove(@PathVariable Long[] socialPlatformIds) {
return toAjax(socialPlatformService.deleteSocialPlatformBySocialPlatformIds(socialPlatformIds));
}
}

View File

@@ -0,0 +1,180 @@
package com.fastbee.data.controller;
import com.fastbee.common.annotation.Log;
import com.fastbee.common.core.controller.BaseController;
import com.fastbee.common.core.domain.AjaxResult;
import com.fastbee.common.core.page.TableDataInfo;
import com.fastbee.common.enums.BusinessType;
import com.fastbee.common.utils.StringUtils;
import com.fastbee.common.utils.poi.ExcelUtil;
import com.fastbee.iot.domain.ThingsModel;
import com.fastbee.iot.model.ImportThingsModelInput;
import com.fastbee.iot.model.ThingsModelPerm;
import com.fastbee.iot.model.varTemp.SyncModel;
import com.fastbee.iot.service.IThingsModelService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
/**
* 物模型Controller
*
* @author kerwincui
* @date 2021-12-16
*/
@RestController
@RequestMapping("/iot/model")
@Api(tags="产品物模型")
public class ThingsModelController extends BaseController
{
@Autowired
private IThingsModelService thingsModelService;
/**
* 查询物模型列表
*/
@PreAuthorize("@ss.hasPermi('iot:device:list')")
@GetMapping("/list")
@ApiOperation("产品物模型分页列表")
public TableDataInfo list(ThingsModel thingsModel)
{
startPage();
List<ThingsModel> list = thingsModelService.selectThingsModelList(thingsModel);
return getDataTable(list);
}
/**
* 查询物模型对应设备分享权限
*/
@PreAuthorize("@ss.hasPermi('iot:device:list')")
@GetMapping("/permList/{productId}")
@ApiOperation("查询物模型对应设备分享权限")
public AjaxResult permList(@PathVariable Long productId)
{
List<ThingsModelPerm> list = thingsModelService.selectThingsModelPermList(productId);
return AjaxResult.success(list);
}
/**
* 获取物模型详细信息
*/
@PreAuthorize("@ss.hasPermi('iot:device:query')")
@GetMapping(value = "/{modelId}")
@ApiOperation("获取产品物模型详情")
public AjaxResult getInfo(@PathVariable("modelId") Long modelId)
{
return AjaxResult.success(thingsModelService.selectThingsModelByModelId(modelId));
}
/**
* 新增物模型
*/
@PreAuthorize("@ss.hasPermi('iot:device:add')")
@Log(title = "物模型", businessType = BusinessType.INSERT)
@PostMapping
@ApiOperation("添加产品物模型")
public AjaxResult add(@RequestBody ThingsModel thingsModel)
{
int result=thingsModelService.insertThingsModel(thingsModel);
if(result==1){
return AjaxResult.success();
}else if(result==2){
return AjaxResult.error("产品下的标识符不能重复");
}else{
return AjaxResult.error();
}
}
@Log(title = "导入物模型",businessType = BusinessType.INSERT)
@PostMapping("/import")
@ApiOperation("导入通用物模型")
public AjaxResult ImportByTemplateIds(@RequestBody ImportThingsModelInput input){
int repeatCount=thingsModelService.importByTemplateIds(input);
if(repeatCount==0){
return AjaxResult.success("数据导入成功");
}else{
return AjaxResult.success(repeatCount+"条数据未导入,标识符重复");
}
}
/**
* 修改物模型
*/
@PreAuthorize("@ss.hasPermi('iot:device:edit')")
@Log(title = "物模型", businessType = BusinessType.UPDATE)
@PutMapping
@ApiOperation("修改产品物模型")
public AjaxResult edit(@RequestBody ThingsModel thingsModel)
{
int result=thingsModelService.updateThingsModel(thingsModel);
if(result==1){
return AjaxResult.success();
}else if(result==2){
return AjaxResult.error("产品下的标识符不能重复");
}else{
return AjaxResult.error();
}
}
/**
* 删除物模型
*/
@PreAuthorize("@ss.hasPermi('iot:device:remove')")
@Log(title = "物模型", businessType = BusinessType.DELETE)
@DeleteMapping("/{modelIds}")
@ApiOperation("批量删除产品物模型")
public AjaxResult remove(@PathVariable Long[] modelIds)
{
return toAjax(thingsModelService.deleteThingsModelByModelIds(modelIds));
}
/**
* 获取缓存的JSON物模型
*/
@PreAuthorize("@ss.hasPermi('iot:device:query')")
@GetMapping(value = "/cache/{productId}")
@ApiOperation("获取缓存的JSON物模型")
public AjaxResult getCacheThingsModelByProductId(@PathVariable("productId") Long productId)
{
return AjaxResult.success("操作成功",thingsModelService.getCacheThingsModelByProductId(productId));
}
@ApiOperation(value = "物模型导入模板")
@PostMapping("/temp")
public void temp(HttpServletResponse response){
ExcelUtil<ThingsModel> excelUtil = new ExcelUtil<>(ThingsModel.class);
excelUtil.importTemplateExcel(response,"采集点");
}
/**
* 导入采集点
*/
@PreAuthorize("@ss.hasPermi('iot:point:import')")
@ApiOperation(value = "采集点导入")
@PostMapping(value = "/importData")
public AjaxResult importData(MultipartFile file, Integer tempSlaveId) throws Exception{
ExcelUtil<ThingsModel> excelUtil = new ExcelUtil<>(ThingsModel.class);
List<ThingsModel> list = excelUtil.importExcel(file.getInputStream());
String result = thingsModelService.importData(list, tempSlaveId);
return AjaxResult.success(result);
}
@PreAuthorize("@ss.hasPermi('iot:device:edit')")
@Log(title = "物模型", businessType = BusinessType.UPDATE)
@PostMapping("/synchron")
@ApiOperation("同步采集点模板至产品物模型")
public AjaxResult synchron(@RequestBody SyncModel model)
{
thingsModelService.synchronizeVarTempToProduct(model.getProductIds(), model.getTemplateId());
return AjaxResult.success();
}
}

View File

@@ -0,0 +1,147 @@
package com.fastbee.data.controller;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import com.fastbee.common.core.domain.entity.SysRole;
import com.fastbee.common.core.domain.entity.SysUser;
import com.fastbee.iot.domain.ThingsModel;
import com.fastbee.iot.domain.VarTemp;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fastbee.common.annotation.Log;
import com.fastbee.common.core.controller.BaseController;
import com.fastbee.common.core.domain.AjaxResult;
import com.fastbee.common.enums.BusinessType;
import com.fastbee.iot.domain.ThingsModelTemplate;
import com.fastbee.iot.service.IThingsModelTemplateService;
import com.fastbee.common.utils.poi.ExcelUtil;
import com.fastbee.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import static com.fastbee.common.utils.SecurityUtils.getLoginUser;
/**
* 通用物模型Controller
*
* @author kerwincui
* @date 2021-12-16
*/
@RestController
@RequestMapping("/iot/template")
@Api(tags = "通用物模型")
public class ThingsModelTemplateController extends BaseController {
@Autowired
private IThingsModelTemplateService thingsModelTemplateService;
/**
* 查询通用物模型列表
*/
@PreAuthorize("@ss.hasPermi('iot:template:list')")
@GetMapping("/list")
@ApiOperation("通用物模型分页列表")
public TableDataInfo list(ThingsModelTemplate thingsModelTemplate) {
startPage();
return getDataTable(thingsModelTemplateService.selectThingsModelTemplateList(thingsModelTemplate));
}
/**
* 导出通用物模型列表
*/
@PreAuthorize("@ss.hasPermi('iot:template:export')")
@Log(title = "通用物模型", businessType = BusinessType.EXPORT)
@PostMapping("/export")
@ApiOperation("导出通用物模型")
public void export(HttpServletResponse response, ThingsModelTemplate thingsModelTemplate) {
List<ThingsModelTemplate> list = thingsModelTemplateService.selectThingsModelTemplateList(thingsModelTemplate);
ExcelUtil<ThingsModelTemplate> util = new ExcelUtil<ThingsModelTemplate>(ThingsModelTemplate.class);
util.exportExcel(response, list, "通用物模型数据");
}
/**
* 获取通用物模型详细信息
*/
@PreAuthorize("@ss.hasPermi('iot:template:query')")
@GetMapping(value = "/{templateId}")
@ApiOperation("获取通用物模型详情")
public AjaxResult getInfo(@PathVariable("templateId") Long templateId) {
return AjaxResult.success(thingsModelTemplateService.selectThingsModelTemplateByTemplateId(templateId));
}
/**
* 新增通用物模型
*/
@PreAuthorize("@ss.hasPermi('iot:template:add')")
@Log(title = "通用物模型", businessType = BusinessType.INSERT)
@PostMapping
@ApiOperation("添加通用物模型")
public AjaxResult add(@RequestBody ThingsModelTemplate thingsModelTemplate) {
return toAjax(thingsModelTemplateService.insertThingsModelTemplate(thingsModelTemplate));
}
/**
* 修改通用物模型
*/
@PreAuthorize("@ss.hasPermi('iot:template:edit')")
@Log(title = "通用物模型", businessType = BusinessType.UPDATE)
@PutMapping
@ApiOperation("修改通用物模型")
public AjaxResult edit(@RequestBody ThingsModelTemplate thingsModelTemplate) {
return toAjax(thingsModelTemplateService.updateThingsModelTemplate(thingsModelTemplate));
}
/**
* 删除通用物模型
*/
@PreAuthorize("@ss.hasPermi('iot:template:remove')")
@Log(title = "通用物模型", businessType = BusinessType.DELETE)
@DeleteMapping("/{templateIds}")
@ApiOperation("批量删除通用物模型")
public AjaxResult remove(@PathVariable Long[] templateIds) {
return toAjax(thingsModelTemplateService.deleteThingsModelTemplateByTemplateIds(templateIds));
}
@ApiOperation(value = "物模型导入模板")
@PostMapping("/temp")
public void temp(HttpServletResponse response) {
ExcelUtil<ThingsModelTemplate> excelUtil = new ExcelUtil<>(ThingsModelTemplate.class);
excelUtil.importTemplateExcel(response, "采集点");
}
/**
* 导入采集点
*/
@PreAuthorize("@ss.hasPermi('iot:template:add')")
@ApiOperation(value = "采集点导入")
@PostMapping(value = "/importData")
public AjaxResult importData(MultipartFile file, String tempSlaveId) throws Exception {
ExcelUtil<ThingsModelTemplate> excelUtil = new ExcelUtil<>(ThingsModelTemplate.class);
List<ThingsModelTemplate> list = excelUtil.importExcel(file.getInputStream());
String result = thingsModelTemplateService.importData(list, tempSlaveId);
return AjaxResult.success(result);
}
/**
* 根据模板id查询采集点数据
*/
@ApiOperation("根据模板id查询采集点数据")
@PreAuthorize("@ss.hasPermi('iot:template:query')")
@GetMapping("/getPoints")
public TableDataInfo getPoints(VarTemp varTemp) {
startPage();
List<ThingsModelTemplate> result = thingsModelTemplateService.selectAllByTemplateId(varTemp.getTemplateId());
return getDataTable(result);
}
}

View File

@@ -0,0 +1,450 @@
package com.fastbee.data.controller;
import com.alibaba.fastjson2.JSONObject;
import com.fastbee.common.ProtocolDeCodeService;
import com.fastbee.common.annotation.Log;
import com.fastbee.common.config.RuoYiConfig;
import com.fastbee.common.constant.Constants;
import com.fastbee.common.core.controller.BaseController;
import com.fastbee.common.core.domain.AjaxResult;
import com.fastbee.common.core.domain.entity.SysUser;
import com.fastbee.common.core.iot.response.DeCodeBo;
import com.fastbee.common.core.page.TableDataInfo;
import com.fastbee.common.core.protocol.modbus.ModbusCode;
import com.fastbee.common.enums.BusinessType;
import com.fastbee.common.exception.file.FileNameLengthLimitExceededException;
import com.fastbee.common.utils.StringUtils;
import com.fastbee.common.utils.file.FileUploadUtils;
import com.fastbee.common.utils.file.FileUtils;
import com.fastbee.common.utils.gateway.mq.TopicsUtils;
import com.fastbee.iot.domain.Device;
import com.fastbee.iot.model.*;
import com.fastbee.iot.model.ThingsModels.ThingsModelShadow;
import com.fastbee.iot.service.IDeviceService;
import com.fastbee.iot.service.IToolService;
import com.fastbee.iot.util.VelocityInitializer;
import com.fastbee.iot.util.VelocityUtils;
import com.fastbee.mq.model.ReportDataBo;
import com.fastbee.mq.mqttClient.MqttClientConfig;
import com.fastbee.mq.mqttClient.PubMqttClient;
import com.fastbee.mq.service.IMqttMessagePublish;
import com.fastbee.mqtt.model.PushMessageBo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.netty.buffer.ByteBufUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static com.fastbee.common.utils.file.FileUploadUtils.getExtension;
/**
* 产品分类Controller
*
* @author kerwincui
* @date 2021-12-16
*/
@Api(tags = "工具相关")
@RestController
@RequestMapping("/iot/tool")
public class ToolController extends BaseController {
private static final Logger log = LoggerFactory.getLogger(ToolController.class);
@Autowired
private IDeviceService deviceService;
@Autowired
private IMqttMessagePublish messagePublish;
@Autowired
private MqttClientConfig mqttConfig;
@Autowired
private IToolService toolService;
// 令牌秘钥
@Value("${token.secret}")
private String secret;
@Resource
private ProtocolDeCodeService deCodeService;
@Resource
private PubMqttClient mqttClient;
/**
* 用户注册
*/
@ApiOperation("用户注册")
@PostMapping("/register")
public AjaxResult register(@RequestBody RegisterUserInput user) {
String msg = toolService.register(user);
return StringUtils.isEmpty(msg) ? success() : error(msg);
}
/**
* 获取用户列表
*/
@ApiOperation("获取用户列表")
@GetMapping("/userList")
public TableDataInfo list(SysUser user)
{
startPage();
List<SysUser> list = toolService.selectUserList(user);
return getDataTable(list);
}
@ApiOperation("mqtt认证")
@PostMapping("/mqtt/auth")
public ResponseEntity mqttAuth(@RequestParam String clientid, @RequestParam String username, @RequestParam String password) throws Exception {
if (clientid.startsWith("server")) {
// 服务端认证:配置的账号密码认证
if (mqttConfig.getUsername().equals(username) && mqttConfig.getPassword().equals(password)) {
log.info("-----------服务端mqtt认证成功,clientId:" + clientid + "---------------");
return ResponseEntity.ok().body("ok");
} else {
return toolService.returnUnauthorized(new MqttAuthenticationModel(clientid, username, password), "mqtt账号和密码与认证服务器配置不匹配");
}
} else if (clientid.startsWith("web") || clientid.startsWith("phone")) {
// web端和移动端认证token认证
String token = password;
if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX)) {
token = token.replace(Constants.TOKEN_PREFIX, "");
}
try {
Claims claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
log.info("-----------移动端/Web端mqtt认证成功,clientId:" + clientid + "---------------");
return ResponseEntity.ok().body("ok");
} catch (Exception ex) {
return toolService.returnUnauthorized(new MqttAuthenticationModel(clientid, username, password), ex.getMessage());
}
} else {
// 替换为整合之后的接口
return toolService.clientAuth(clientid, username, password);
}
}
@ApiOperation("mqtt认证")
@PostMapping("/mqtt/authv5")
public ResponseEntity mqttAuthv5(@RequestBody JSONObject json) throws Exception {
log.info("-----------auth-json:" + json + "---------------");
String clientid = json.getString("clientid");
String username = json.getString("username");
String password = json.getString("password");
String peerhost = json.getString("peerhost"); // 源IP地址
JSONObject ret = new JSONObject();
ret.put("is_superuser", false);
if (clientid.startsWith("server")) {
// 服务端认证:配置的账号密码认证
if (mqttConfig.getUsername().equals(username) && mqttConfig.getPassword().equals(password)) {
log.info("-----------服务端mqtt认证成功,clientId:" + clientid + "---------------");
ret.put("result", "allow");
return ResponseEntity.ok().body(ret);
} else {
ret.put("result", "deny");
return ResponseEntity.ok().body(ret);
}
} else if (clientid.startsWith("web") || clientid.startsWith("phone")) {
// web端和移动端认证token认证
String token = password;
if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX)) {
token = token.replace(Constants.TOKEN_PREFIX, "");
}
try {
Claims claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
log.info("-----------移动端/Web端mqtt认证成功,clientId:" + clientid + "---------------");
ret.put("result", "allow");
return ResponseEntity.ok().body(ret);
} catch (Exception ex) {
ret.put("result", "deny");
return ResponseEntity.ok().body(ret);
}
} else {
// 替换为整合之后的接口
return toolService.clientAuthv5(clientid, username, password);
}
}
@ApiOperation("mqtt钩子处理")
@PostMapping("/mqtt/webhook")
public void webHookProcess(@RequestBody MqttClientConnectModel model) {
try {
System.out.println("webhook:" + model.getAction());
// 过滤服务端、web端和手机端
if (model.getClientid().startsWith("server") || model.getClientid().startsWith("web") || model.getClientid().startsWith("phone")) {
return;
}
// 设备端认证加密认证E和简单认证S配置的账号密码认证
String[] clientArray = model.getClientid().split("&");
String authType = clientArray[0];
String deviceNumber = clientArray[1];
Long productId = Long.valueOf(clientArray[2]);
Long userId = Long.valueOf(clientArray[3]);
Device device = deviceService.selectShortDeviceBySerialNumber(deviceNumber);
ReportDataBo ruleBo = new ReportDataBo();
ruleBo.setProductId(device.getProductId());
ruleBo.setSerialNumber(device.getSerialNumber());
// 设备状态1-未激活2-禁用3-在线4-离线)
if (model.getAction().equals("client_disconnected")) {
device.setStatus(4);
deviceService.updateDeviceStatusAndLocation(device, "");
// 设备掉线后发布设备状态
messagePublish.publishStatus(device.getProductId(), device.getSerialNumber(), 4, device.getIsShadow(),device.getRssi());
// 清空保留消息,上线后发布新的属性功能保留消息
messagePublish.publishProperty(device.getProductId(), device.getSerialNumber(), null,0);
messagePublish.publishFunction(device.getProductId(), device.getSerialNumber(), null,0);
} else if (model.getAction().equals("client_connected")) {
device.setStatus(3);
deviceService.updateDeviceStatusAndLocation(device, model.getIpaddress());
// 设备上线后发布设备状态
messagePublish.publishStatus(device.getProductId(), device.getSerialNumber(), 3, device.getIsShadow(),device.getRssi());
// 影子模式,发布属性和功能
if (device.getIsShadow() == 1) {
ThingsModelShadow shadow = deviceService.getDeviceShadowThingsModel(device);
if (shadow.getProperties().size() > 0) {
messagePublish.publishProperty(device.getProductId(), device.getSerialNumber(), shadow.getProperties(),3);
}
if (shadow.getFunctions().size() > 0) {
messagePublish.publishFunction(device.getProductId(), device.getSerialNumber(), shadow.getFunctions(),3);
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
log.error("发生错误:" + ex.getMessage());
}
}
@ApiOperation("mqtt钩子处理")
@PostMapping("/mqtt/webhookv5")
public void webHookProcessv5(@RequestBody JSONObject json) {
try {
String clientid = json.getString("clientid");
String event = json.getString("event");
String peername = json.getString("peername"); // 类似 127.0.0.111.11.11.11:8812
String ipAddress=peername;
if(peername.indexOf(":")!=-1){
ipAddress = peername.substring(0,peername.indexOf(":"));
}
log.info("webhook:" + event + ",clientid:" + clientid);
// 过滤服务端、web端和手机端
if (clientid.startsWith("server") || clientid.startsWith("web") || clientid.startsWith("phone")) {
return;
}
// 设备端认证加密认证E和简单认证S配置的账号密码认证
String[] clientArray = clientid.split("&");
String deviceNumber = clientArray[1];
Device device = deviceService.selectShortDeviceBySerialNumber(deviceNumber);
ReportDataBo ruleBo = new ReportDataBo();
ruleBo.setProductId(device.getProductId());
ruleBo.setSerialNumber(device.getSerialNumber());
// 设备状态1-未激活2-禁用3-在线4-离线)
if (event.equals("client.disconnected")) {
device.setStatus(4);
deviceService.updateDeviceStatusAndLocation(device, "");
// 设备掉线后发布设备状态
messagePublish.publishStatus(device.getProductId(), device.getSerialNumber(), 4, device.getIsShadow(),device.getRssi());
// 清空保留消息,上线后发布新的属性功能保留消息
messagePublish.publishProperty(device.getProductId(), device.getSerialNumber(), null,0);
messagePublish.publishFunction(device.getProductId(), device.getSerialNumber(), null,0);
} else if (event.equals("client.connected")) {
device.setStatus(3);
deviceService.updateDeviceStatusAndLocation(device, ipAddress);
// 设备掉线后发布设备状态
messagePublish.publishStatus(device.getProductId(), device.getSerialNumber(), 3, device.getIsShadow(),device.getRssi());
} else if(event.equals("session.subscribed")){
// 影子模式,发布属性和功能
if (device.getIsShadow() == 1) {
ThingsModelShadow shadow = deviceService.getDeviceShadowThingsModel(device);
if (shadow.getProperties().size() > 0) {
messagePublish.publishProperty(device.getProductId(), device.getSerialNumber(), shadow.getProperties(),3);
}
if (shadow.getFunctions().size() > 0) {
messagePublish.publishFunction(device.getProductId(), device.getSerialNumber(), shadow.getFunctions(),3);
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
log.error("发生错误:" + ex.getMessage());
}
}
@ApiOperation("获取NTP时间")
@GetMapping("/ntp")
public JSONObject ntp(@RequestParam Long deviceSendTime) {
JSONObject ntpJson = new JSONObject();
ntpJson.put("deviceSendTime", deviceSendTime);
ntpJson.put("serverRecvTime", System.currentTimeMillis());
ntpJson.put("serverSendTime", System.currentTimeMillis());
return ntpJson;
}
/**
* 文件上传
*/
@PostMapping("/upload")
@ApiOperation("文件上传")
public AjaxResult uploadFile(MultipartFile file) throws Exception {
try {
String filePath = RuoYiConfig.getProfile();
// 文件名长度限制
int fileNamelength = file.getOriginalFilename().length();
if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) {
throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
}
// 文件类型限制
// assertAllowed(file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
// 获取文件名和文件类型
String fileName = file.getOriginalFilename();
String extension = getExtension(file);
//设置日期格式
SimpleDateFormat df = new SimpleDateFormat("yyyy-MMdd-HHmmss");
fileName = "/iot/" + getLoginUser().getUserId().toString() + "/" + df.format(new Date()) + "." + extension;
//创建目录
File desc = new File(filePath + File.separator + fileName);
if (!desc.exists()) {
if (!desc.getParentFile().exists()) {
desc.getParentFile().mkdirs();
}
}
// 存储文件
file.transferTo(desc);
String url = "/profile" + fileName;
AjaxResult ajax = AjaxResult.success();
ajax.put("fileName", url);
ajax.put("url", url);
return ajax;
} catch (Exception e) {
return AjaxResult.error(e.getMessage());
}
}
/**
* 下载文件
*/
@ApiOperation("文件下载")
@GetMapping("/download")
public void download(String fileName, HttpServletResponse response, HttpServletRequest request) {
try {
// if (!FileUtils.checkAllowDownload(fileName)) {
// throw new Exception(StringUtils.format("文件名称({})非法,不允许下载。 ", fileName));
// }
String filePath = RuoYiConfig.getProfile();
// 资源地址
String downloadPath = filePath + fileName.replace("/profile", "");
// 下载名称
String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
FileUtils.setAttachmentResponseHeader(response, downloadName);
FileUtils.writeBytes(downloadPath, response.getOutputStream());
} catch (Exception e) {
log.error("下载文件失败", e);
}
}
/**
* 批量生成代码
*/
@Log(title = "SDK生成", businessType = BusinessType.GENCODE)
@GetMapping("/genSdk")
@ApiOperation("生成SDK")
public void genSdk(HttpServletResponse response, int deviceChip) throws IOException {
byte[] data = downloadCode(deviceChip);
genSdk(response, data);
}
/**
* 生成zip文件
*/
private void genSdk(HttpServletResponse response, byte[] data) throws IOException {
response.reset();
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
response.setHeader("Content-Disposition", "attachment; filename=\"fastbee.zip\"");
response.addHeader("Content-Length", "" + data.length);
response.setContentType("application/octet-stream; charset=UTF-8");
IOUtils.write(data, response.getOutputStream());
}
/**
* 批量生成代码(下载方式)
*
* @param deviceChip
* @return 数据
*/
public byte[] downloadCode(int deviceChip) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream);
// generatorCode(deviceChip, zip);
IOUtils.closeQuietly(zip);
return outputStream.toByteArray();
}
/**
* 查询表信息并生成代码
*/
private void generatorCode(int deviceChip, ZipOutputStream zip) {
VelocityInitializer.initVelocity();
VelocityContext context = VelocityUtils.prepareContext(deviceChip);
// 获取模板列表
List<String> templates = VelocityUtils.getTemplateList("");
for (String template : templates) {
// 渲染模板
StringWriter sw = new StringWriter();
Template tpl = Velocity.getTemplate(template, Constants.UTF8);
tpl.merge(context, sw);
try {
// 添加到zip
zip.putNextEntry(new ZipEntry(VelocityUtils.getFileName(template)));
IOUtils.write(sw.toString(), zip, Constants.UTF8);
IOUtils.closeQuietly(sw);
zip.flush();
zip.closeEntry();
} catch (IOException e) {
System.out.println("渲染模板失败");
}
}
}
@GetMapping("/getTopics")
@ApiOperation("获取所有下发的topic")
public AjaxResult getTopics(Boolean isSimulate){
return AjaxResult.success(TopicsUtils.getAllGet(isSimulate));
}
@GetMapping("/decode")
@ApiOperation("指令编码")
public AjaxResult decode(DeCodeBo bo){
return AjaxResult.success(deCodeService.protocolDeCode(bo));
}
}

View File

@@ -0,0 +1,69 @@
package com.fastbee.data.controller;
import com.fastbee.common.core.controller.BaseController;
import com.fastbee.common.core.domain.AjaxResult;
import com.fastbee.iot.service.IUserSocialProfileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
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;
/**
* 第三方登录平台控制Controller
*
* @author json
* @date 2022-04-24
*/
@Api(tags = "用户社交账户api")
@RestController
@RequestMapping("/iot/social/")
public class UserSocialController extends BaseController {
@Autowired
private IUserSocialProfileService iUserSocialProfileService;
/**
* 绑定
*
* @param bindId 绑定id
* @return
*/
@GetMapping("/bindId/{bindId}")
@ApiOperation("绑定api")
@ApiImplicitParam(name = "bindId", value = "绑定bindId", required = true, dataType = "String", paramType = "path", dataTypeClass = String.class)
public AjaxResult bindUser(@PathVariable String bindId) {
return iUserSocialProfileService.bindUser(bindId, getUserId());
}
/**
* 绑定
*
* @param platform 绑定类型
* @return
*/
@GetMapping("/bind/{platform}")
@ApiOperation("绑定跳转api")
@ApiImplicitParam(name = "platform", value = "绑定platform", required = true, dataType = "String", paramType = "path", dataTypeClass = String.class)
public AjaxResult bind(@PathVariable String platform) {
return iUserSocialProfileService.bindSocialAccount(platform);
}
/**
* 解绑
*
* @param socialUserId 用户社交平台Id
* @return
*/
@GetMapping("/unbind/{socialUserId}")
@ApiOperation("解绑api")
@ApiImplicitParam(name = "socialUserId", value = "绑定socialId", required = true, dataType = "Long", paramType = "path", dataTypeClass = Long.class)
public AjaxResult unbind(@PathVariable Long socialUserId) {
return iUserSocialProfileService.unbindSocialAccount(socialUserId, getUserId());
}
}

View File

@@ -0,0 +1,72 @@
package com.fastbee.data.controller.dashBoard;
import com.fastbee.common.constant.FastBeeConstant;
import com.fastbee.common.core.domain.AjaxResult;
import com.fastbee.common.core.redis.RedisCache;
import com.fastbee.iot.model.dashBoard.DashMqttMetrics;
import com.fastbee.iot.model.dashBoard.DashMqttStat;
import com.fastbee.mqtt.manager.ClientManager;
import com.fastbee.mqtt.manager.RetainMsgManager;
import com.fastbee.base.service.ISessionStore;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
* 首页面板和大屏数据
*
* @author gsb
* @date 2023/3/27 17:00
*/
@Api(tags = "首页面板和大屏数据")
@RestController
@RequestMapping("/bashBoard")
public class DashBoardController {
@Resource
private RedisCache redisCache;
@Resource
private ISessionStore sessionStore;
@GetMapping("/stats")
@ApiOperation("mqtt状态数据")
public AjaxResult stats() {
DashMqttStat stat = DashMqttStat.builder()
.connection_count(sessionStore.getSessionMap().size())
.connection_total(getTotal(FastBeeConstant.REDIS.MESSAGE_CONNECT_TOTAL))
.subscription_count(ClientManager.topicMap.size())
.subscription_total(getTotal(FastBeeConstant.REDIS.MESSAGE_SUBSCRIBE_TOTAL))
.retain_count(RetainMsgManager.getSize())
.retain_total(getTotal(FastBeeConstant.REDIS.MESSAGE_RETAIN_TOTAL))
.session_count(sessionStore.getSessionMap().size())
.session_total(getTotal(FastBeeConstant.REDIS.MESSAGE_CONNECT_TOTAL))
.build();
return AjaxResult.success(stat);
}
@GetMapping("/metrics")
@ApiOperation("mqtt统计")
public AjaxResult metrics() {
DashMqttMetrics metrics = DashMqttMetrics.builder()
.send_total(getTotal(FastBeeConstant.REDIS.MESSAGE_SEND_TOTAL))
.receive_total(getTotal(FastBeeConstant.REDIS.MESSAGE_RECEIVE_TOTAL))
.auth_total(getTotal(FastBeeConstant.REDIS.MESSAGE_AUTH_TOTAL))
.connect_total(getTotal(FastBeeConstant.REDIS.MESSAGE_CONNECT_TOTAL))
.subscribe_total(getTotal(FastBeeConstant.REDIS.MESSAGE_SUBSCRIBE_TOTAL))
.today_received(getTotal(FastBeeConstant.REDIS.MESSAGE_RECEIVE_TODAY))
.today_send(getTotal(FastBeeConstant.REDIS.MESSAGE_SEND_TODAY))
.build();
return AjaxResult.success(metrics);
}
public Integer getTotal(String key) {
return redisCache.getCacheObject(key) == null ? 0 : redisCache.getCacheObject(key);
}
}

View File

@@ -0,0 +1,121 @@
package com.fastbee.data.controller.netty;
import com.fastbee.base.service.ISessionStore;
import com.fastbee.base.session.Session;
import com.fastbee.common.core.controller.BaseController;
import com.fastbee.common.core.domain.AjaxResult;
import com.fastbee.common.utils.StringUtils;
import com.fastbee.common.utils.gateway.mq.Topics;
import com.fastbee.mqtt.manager.ClientManager;
import com.fastbee.mqtt.manager.SessionManger;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
/**
* NETTY客户端可视化
*
* @author gsb
* @date 2023/3/23 14:51
*/
@RestController
@RequestMapping("/iot/mqtt")
@Api(tags = "Netty可视化")
@Slf4j
public class NettyManagerController extends BaseController {
@Resource
private ISessionStore sessionStore;
/**
* 客户端管理列表
* @param pageSize 分页大小
* @param pageNum 页数
* @param clientId 查询客户端id
* @param serverCode 服务端类型编码 MQTT/TCP/UDP
* @param isClient 是否只显示设备端 1-是/0或null-否
* @return 客户端列表
*/
@GetMapping("/clients")
@ApiOperation("netty客户端列表")
public AjaxResult clients(Integer pageSize, Integer pageNum, String clientId, String serverCode,Integer isClient) {
List<Session> list = new ArrayList<>();
if (StringUtils.isEmpty(clientId)) {
ConcurrentHashMap<String, Session> sourceMap = sessionStore.getSessionMap();
ConcurrentHashMap<String, Session> selectMap = new ConcurrentHashMap<>();
sourceMap.forEach((key, value) -> {
if (serverCode.equals(value.getServerType().getCode())) {
if (null != isClient && isClient == 1){
if (!key.startsWith("server") && !key.startsWith("web") && !key.startsWith("phone") && !key.startsWith("test")){
selectMap.put(key,value);
}
}else {
selectMap.put(key, value);
}
}
});
Map<String, Session> sessionMap = sessionStore.listPage(selectMap, pageSize, pageNum);
List<Session> result = new ArrayList<>(sessionMap.values());
for (Session session : result) {
Map<String, Boolean> topicMap = ClientManager.clientTopicMap.get(session.getClientId());
if (topicMap != null) {
List<Topics> topicsList = new ArrayList<>();
topicMap.keySet().forEach(topic -> {
Topics tBo = new Topics();
tBo.setTopicName(topic);
topicsList.add(tBo);
});
session.setTopics(topicsList);
session.setTopicCount(topicMap.size());
} else {
session.setTopicCount(0);
}
list.add(session);
}
return AjaxResult.success(list, selectMap.size());
} else {
List<Session> result = new ArrayList<>();
Session session = sessionStore.getSession(clientId);
if (session != null) {
Map<String, Boolean> topicMap = ClientManager.clientTopicMap.get(session.getClientId());
if (topicMap != null) {
List<Topics> topicsList = new ArrayList<>();
topicMap.keySet().forEach(topic -> {
Topics tBo = new Topics();
tBo.setTopicName(topic);
topicsList.add(tBo);
});
session.setTopics(topicsList);
session.setTopicCount(topicMap.size());
} else {
session.setTopicCount(0);
}
if (serverCode.equals(session.getServerType().getCode())) {
result.add(session);
}
}
return AjaxResult.success(result, result.size());
}
}
@GetMapping("/client/out")
@ApiOperation("netty客户端踢出")
public AjaxResult clientOut(String clientId){
Session session = sessionStore.getSession(clientId);
Optional.ofNullable(session).orElseThrow(() -> new SecurityException("客户端不存在"));
SessionManger.removeClient(clientId);
return AjaxResult.success();
}
}

View File

@@ -0,0 +1,114 @@
package com.fastbee.data.controller.protocol;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fastbee.common.annotation.Log;
import com.fastbee.common.core.controller.BaseController;
import com.fastbee.common.core.domain.AjaxResult;
import com.fastbee.common.enums.BusinessType;
import com.fastbee.iot.domain.Protocol;
import com.fastbee.iot.service.IProtocolService;
import com.fastbee.common.utils.poi.ExcelUtil;
import com.fastbee.common.core.page.TableDataInfo;
/**
* 协议Controller
*
* @author kerwincui
* @date 2022-12-07
*/
@Api(tags = "协议")
@RestController
@RequestMapping("/iot/protocol")
public class ProtocolController extends BaseController
{
@Autowired
private IProtocolService protocolService;
/**
* 查询协议列表
*/
@ApiOperation("查询协议列表")
@PreAuthorize("@ss.hasPermi('iot:protocol:list')")
@GetMapping("/list")
public TableDataInfo list(Protocol protocol)
{
startPage();
List<Protocol> list = protocolService.selectProtocolList(protocol);
return getDataTable(list);
}
/**
* 导出协议列表
*/
@ApiOperation("导出协议列表")
@PreAuthorize("@ss.hasPermi('iot:protocol:export')")
@Log(title = "协议", businessType = BusinessType.EXPORT)
@PostMapping("/export")
public void export(HttpServletResponse response, Protocol protocol)
{
List<Protocol> list = protocolService.selectProtocolList(protocol);
ExcelUtil<Protocol> util = new ExcelUtil<Protocol>(Protocol.class);
util.exportExcel(response, list, "协议数据");
}
/**
* 获取协议详细信息
*/
@ApiOperation("获取协议详细信息")
@PreAuthorize("@ss.hasPermi('iot:protocol:query')")
@GetMapping(value = "/{id}")
public AjaxResult getInfo(@PathVariable("id") Long id)
{
return AjaxResult.success(protocolService.selectProtocolById(id));
}
/**
* 新增协议
*/
@ApiOperation("新增协议")
@PreAuthorize("@ss.hasPermi('iot:protocol:add')")
@Log(title = "协议", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@RequestBody Protocol protocol)
{
return toAjax(protocolService.insertProtocol(protocol));
}
/**
* 修改协议
*/
@ApiOperation("修改协议")
@PreAuthorize("@ss.hasPermi('iot:protocol:edit')")
@Log(title = "协议", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@RequestBody Protocol protocol)
{
return toAjax(protocolService.updateProtocol(protocol));
}
/**
* 删除协议
*/
@ApiOperation("删除协议")
@PreAuthorize("@ss.hasPermi('iot:protocol:remove')")
@Log(title = "协议", businessType = BusinessType.DELETE)
@DeleteMapping("/{ids}")
public AjaxResult remove(@PathVariable Long[] ids)
{
return toAjax(protocolService.deleteProtocolByIds(ids));
}
}

View File

@@ -0,0 +1,119 @@
package com.fastbee.data.controller.runtime;
import com.alibaba.fastjson2.JSONObject;
import com.fastbee.common.core.controller.BaseController;
import com.fastbee.common.core.domain.AjaxResult;
import com.fastbee.common.core.mq.InvokeReqDto;
import com.fastbee.common.core.page.TableDataInfo;
import com.fastbee.common.core.redis.RedisCache;
import com.fastbee.common.enums.ThingsModelType;
import com.fastbee.common.exception.ServiceException;
import com.fastbee.common.utils.StringUtils;
import com.fastbee.iot.domain.DeviceLog;
import com.fastbee.iot.domain.FunctionLog;
import com.fastbee.iot.service.IDeviceRuntimeService;
import com.fastbee.mq.service.IFunctionInvoke;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;
/**
* 设备运行时数据controller
*
* @author gsb
* @date 2022/12/5 11:52
*/
@RestController
@RequestMapping("/iot/runtime")
@Api(tags = "设备运行数据")
public class DeviceRuntimeController extends BaseController {
@Autowired
private IFunctionInvoke functionInvoke;
@Resource
private IDeviceRuntimeService runtimeService;
/**
* 服务下发
* 例如modbus 格式如下
*
* @see InvokeReqDto#getRemoteCommand()
* key = 寄存器地址
* value = 寄存器地址值
* <p>
* 其他协议 key = identifier
* value = 值
* {
* "serialNumber": "860061060282358",
* "productId": "2",
* "identifier": "temp",
* "remoteCommand": {
* "4": "4"
* }
* }
*/
@PostMapping("/service/invoke")
@PreAuthorize("@ss.hasPermi('iot:service:invoke')")
@ApiOperation(value = "服务下发", httpMethod = "POST", response = AjaxResult.class, notes = "服务下发")
public AjaxResult invoke(@Valid @RequestBody InvokeReqDto reqDto) {
reqDto.setValue(new JSONObject(reqDto.getRemoteCommand()));
String messageId = functionInvoke.invokeNoReply(reqDto);
return AjaxResult.success(messageId);
}
/**
* 根据messageId查询服务回执
*/
@GetMapping(value = "fun/get")
//@PreAuthorize("@ss.hasPermi('iot:service:get')")
@ApiOperation(value = "根据messageId查询服务回执", httpMethod = "GET", response = AjaxResult.class, notes = "根据messageId查询服务回执")
public AjaxResult reply(String serialNumber, String messageId) {
if (StringUtils.isEmpty(messageId) || StringUtils.isEmpty(serialNumber)) {
throw new ServiceException("消息id为空");
}
// TODO - 根据消息id查询
//DeviceTdReq req = new DeviceTdReq();
//req.setImei(serialNumber);
//req.setMessageId(messageId);
//DeviceTdData data = deviceTdService.selectReplyMsg(req);
//return toAjax(data)
return AjaxResult.success();
}
/**
* 实时状态
* @param serialNumber 设备类型
* @param type 物模型类型
* @return 结果
*/
@GetMapping(value = "/runState")
@ApiOperation(value = "实时状态")
public AjaxResult runState(String serialNumber, Integer type,Long productId,Integer slaveId){
ThingsModelType modelType = ThingsModelType.getType(type);
List<DeviceLog> logList = runtimeService.runtimeBySerialNumber(serialNumber, modelType,productId,slaveId);
return AjaxResult.success(logList);
}
/**
* 设备服务下发日志
*/
@GetMapping(value = "/funcLog")
@ApiOperation(value = "设备服务下发日志")
public TableDataInfo funcLog(String serialNumber){
startPage();
List<FunctionLog> logList = runtimeService.runtimeReply(serialNumber);
return getDataTable(logList);
}
}

View File

@@ -0,0 +1,127 @@
package com.fastbee.data.controller.wechat;
import com.fastbee.common.core.domain.AjaxResult;
import com.fastbee.common.exception.ServiceException;
import com.fastbee.common.utils.StringUtils;
import com.fastbee.common.wechat.WeChatLoginBody;
import com.fastbee.common.wechat.WeChatLoginResult;
import com.fastbee.iot.wechat.WeChatService;
import com.fastbee.iot.wechat.vo.WxBindReqVO;
import com.fastbee.iot.wechat.vo.WxCancelBindReqVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 微信相关控制器
* @author fastb
* @date 2023-07-31 11:29
*/
@Api(tags = "微信相关模块")
@RestController
@RequestMapping("/wechat")
public class WeChatController {
@Resource
private WeChatService weChatService;
/**
* 移动应用微信登录
* @param weChatLoginBody 微信登录参数
* @return 登录结果
*/
@ApiOperation("移动应用微信登录")
@PostMapping("/mobileLogin")
public AjaxResult mobileLogin(@RequestBody WeChatLoginBody weChatLoginBody) {
return AjaxResult.success(weChatService.mobileLogin(weChatLoginBody));
}
/**
* 小程序微信登录
* @param weChatLoginBody 微信登录参数
* @return 登录结果
*/
@ApiOperation("小程序微信登录")
@PostMapping("/miniLogin")
public AjaxResult miniLogin(@RequestBody WeChatLoginBody weChatLoginBody) {
WeChatLoginResult weChatLoginResult = weChatService.miniLogin(weChatLoginBody);
return AjaxResult.success(weChatLoginResult);
}
/**
* 小程序、移动应用微信绑定
* @param wxBindReqVO 微信绑定传参类型
* @return 结果
*/
@ApiOperation("小程序、移动应用微信绑定")
@PostMapping("/bind")
public AjaxResult bind(@RequestBody WxBindReqVO wxBindReqVO) {
if (StringUtils.isEmpty(wxBindReqVO.getSourceClient())) {
throw new ServiceException("请传入验证方式");
}
return weChatService.bind(wxBindReqVO);
}
/**
* 取消所有微信绑定
* @param wxCancelBindReqVO 微信解绑传参类型
* @return 结果
*/
@ApiOperation("取消所有微信绑定")
@PostMapping("/cancelBind")
public AjaxResult cancelBind(@RequestBody WxCancelBindReqVO wxCancelBindReqVO) {
if (wxCancelBindReqVO.getVerifyType() == null) {
throw new ServiceException("请传入验证方式");
}
return weChatService.cancelBind(wxCancelBindReqVO);
}
/**
* 网站应用获取微信绑定二维码信息
* @return 二维码信息
*/
@ApiOperation("网站应用获取微信绑定二维码信息")
@GetMapping("/getWxBindQr")
public AjaxResult getWxBindQr(HttpServletRequest httpServletRequest) {
// 返回二维码信息
return weChatService.getWxBindQr(httpServletRequest);
}
/**
* 网站应用内微信扫码绑定回调接口
* @param code 用户凭证
* @param state 时间戳
* @param httpServletRequest 请求信息
* @param httpServletResponse 响应信息
*/
@ApiOperation("网站应用内微信扫码绑定回调地址")
@GetMapping("/wxBind/callback")
public void wxBindCallback(String code, String state, String wxBindId, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
//回调接口
httpServletResponse.sendRedirect(weChatService.wxBindCallback(code, state, wxBindId, httpServletRequest, httpServletResponse));
}
/**
* 网站应用获取微信绑定结果信息
* @param wxBindMsgId 微信绑定结果信息id
* @return msg
*/
@ApiOperation("网站应用获取微信绑定结果信息")
@GetMapping("/getWxBindMsg")
public AjaxResult getWxBindMsg(String wxBindMsgId) {
if (StringUtils.isEmpty(wxBindMsgId)) {
return AjaxResult.error("请传入wxBindMsgId");
}
// 返回二维码信息
return weChatService.getWxBindMsg(wxBindMsgId);
}
}

View File

@@ -0,0 +1,108 @@
package com.fastbee.data.quartz;
import com.fastbee.common.constant.Constants;
import com.fastbee.common.constant.ScheduleConstants;
import com.fastbee.common.utils.ExceptionUtil;
import com.fastbee.common.utils.StringUtils;
import com.fastbee.common.utils.bean.BeanUtils;
import com.fastbee.common.utils.spring.SpringUtils;
import com.fastbee.iot.domain.DeviceJob;
import com.fastbee.quartz.domain.SysJobLog;
import com.fastbee.quartz.service.ISysJobLogService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
/**
* 抽象quartz调用
*
* @author ruoyi
*/
public abstract class AbstractQuartzJob implements Job
{
private static final Logger log = LoggerFactory.getLogger(AbstractQuartzJob.class);
/**
* 线程本地变量
*/
private static ThreadLocal<Date> threadLocal = new ThreadLocal<>();
@Override
public void execute(JobExecutionContext context) throws JobExecutionException
{
DeviceJob deviceJob = new DeviceJob();
BeanUtils.copyBeanProp(deviceJob, context.getMergedJobDataMap().get(ScheduleConstants.TASK_PROPERTIES));
try
{
before(context, deviceJob);
if (deviceJob != null)
{
doExecute(context, deviceJob);
}
after(context, deviceJob, null);
}
catch (Exception e)
{
log.error("任务执行异常 - ", e);
after(context, deviceJob, e);
}
}
/**
* 执行前
*
* @param context 工作执行上下文对象
* @param deviceJob 系统计划任务
*/
protected void before(JobExecutionContext context, DeviceJob deviceJob)
{
threadLocal.set(new Date());
}
/**
* 执行后
*
* @param context 工作执行上下文对象
* @param deviceJob 系统计划任务
*/
protected void after(JobExecutionContext context, DeviceJob deviceJob, Exception e)
{
Date startTime = threadLocal.get();
threadLocal.remove();
final SysJobLog sysJobLog = new SysJobLog();
sysJobLog.setJobName(deviceJob.getJobName());
sysJobLog.setJobGroup(deviceJob.getJobGroup());
sysJobLog.setInvokeTarget(deviceJob.getDeviceName());
sysJobLog.setStartTime(startTime);
sysJobLog.setStopTime(new Date());
long runMs = sysJobLog.getStopTime().getTime() - sysJobLog.getStartTime().getTime();
sysJobLog.setJobMessage(sysJobLog.getJobName() + " 总共耗时:" + runMs + "毫秒");
if (e != null)
{
sysJobLog.setStatus(Constants.FAIL);
String errorMsg = StringUtils.substring(ExceptionUtil.getExceptionMessage(e), 0, 2000);
sysJobLog.setExceptionInfo(errorMsg);
}
else
{
sysJobLog.setStatus(Constants.SUCCESS);
}
// 写入数据库当中
SpringUtils.getBean(ISysJobLogService.class).addJobLog(sysJobLog);
}
/**
* 执行方法,由子类重载
*
* @param context 工作执行上下文对象
* @param deviceJob 系统计划任务
* @throws Exception 执行过程中的异常
*/
protected abstract void doExecute(JobExecutionContext context, DeviceJob deviceJob) throws Exception;
}

View File

@@ -0,0 +1,64 @@
package com.fastbee.data.quartz;
import org.quartz.CronExpression;
import java.text.ParseException;
import java.util.Date;
/**
* cron表达式工具类
*
* @author ruoyi
*
*/
public class CronUtils
{
/**
* 返回一个布尔值代表一个给定的Cron表达式的有效性
*
* @param cronExpression Cron表达式
* @return boolean 表达式是否有效
*/
public static boolean isValid(String cronExpression)
{
return CronExpression.isValidExpression(cronExpression);
}
/**
* 返回一个字符串值,表示该消息无效Cron表达式给出有效性
*
* @param cronExpression Cron表达式
* @return String 无效时返回表达式错误描述,如果有效返回null
*/
public static String getInvalidMessage(String cronExpression)
{
try
{
new CronExpression(cronExpression);
return null;
}
catch (ParseException pe)
{
return pe.getMessage();
}
}
/**
* 返回下一个执行时间根据给定的Cron表达式
*
* @param cronExpression Cron表达式
* @return Date 下次Cron表达式执行时间
*/
public static Date getNextExecution(String cronExpression)
{
try
{
CronExpression cron = new CronExpression(cronExpression);
return cron.getNextValidTimeAfter(new Date(System.currentTimeMillis()));
}
catch (ParseException e)
{
throw new IllegalArgumentException(e.getMessage());
}
}
}

View File

@@ -0,0 +1,77 @@
package com.fastbee.data.quartz;
import com.alibaba.fastjson2.JSON;
import com.fastbee.common.core.thingsModel.ThingsModelSimpleItem;
import com.fastbee.common.utils.spring.SpringUtils;
import com.fastbee.iot.domain.DeviceJob;
import com.fastbee.iot.model.Action;
import com.fastbee.mq.service.IMqttMessagePublish;
import java.util.ArrayList;
import java.util.List;
/**
* 任务执行工具
*
* @author kerwincui
*/
public class JobInvokeUtil {
/**获取消息推送接口*/
private static IMqttMessagePublish messagePublish = SpringUtils.getBean(IMqttMessagePublish.class);
/**
* 执行方法
*
* @param deviceJob 系统任务
*/
public static void invokeMethod(DeviceJob deviceJob) throws Exception {
if (deviceJob.getJobType() == 1) {
System.out.println("------------------------执行定时任务-----------------------------");
List<Action> actions = JSON.parseArray(deviceJob.getActions(), Action.class);
List<ThingsModelSimpleItem> propertys = new ArrayList<>();
List<ThingsModelSimpleItem> functions = new ArrayList<>();
for (int i = 0; i < actions.size(); i++) {
ThingsModelSimpleItem model = new ThingsModelSimpleItem();
model.setId(actions.get(i).getId());
model.setValue(actions.get(i).getValue());
model.setRemark("设备定时");
if (actions.get(i).getType() == 1) {
propertys.add(model);
} else if (actions.get(i).getType() == 2) {
functions.add(model);
}
}
// 发布属性
if (propertys.size() > 0) {
messagePublish.publishProperty(deviceJob.getProductId(), deviceJob.getSerialNumber(), propertys, 0);
}
// 发布功能
if (functions.size() > 0) {
messagePublish.publishFunction(deviceJob.getProductId(), deviceJob.getSerialNumber(), functions, 0);
}
} else if (deviceJob.getJobType() == 2) {
} else if (deviceJob.getJobType() == 3) {
System.out.println("------------------------定时执行场景联动-----------------------------");
List<Action> actions = JSON.parseArray(deviceJob.getActions(), Action.class);
for (int i = 0; i < actions.size(); i++) {
ThingsModelSimpleItem model = new ThingsModelSimpleItem();
model.setId(actions.get(i).getId());
model.setValue(actions.get(i).getValue());
model.setRemark("场景联动定时触发");
if (actions.get(i).getType() == 1) {
List<ThingsModelSimpleItem> propertys = new ArrayList<>();
propertys.add(model);
messagePublish.publishProperty(actions.get(i).getProductId(), actions.get(i).getSerialNumber(), propertys, 0);
} else if (actions.get(i).getType() == 2) {
List<ThingsModelSimpleItem> functions = new ArrayList<>();
functions.add(model);
messagePublish.publishFunction(actions.get(i).getProductId(), actions.get(i).getSerialNumber(), functions, 0);
}
}
}
}
}

View File

@@ -0,0 +1,21 @@
package com.fastbee.data.quartz;
import com.fastbee.iot.domain.DeviceJob;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
/**
* 定时任务处理(禁止并发执行)
*
* @author ruoyi
*
*/
@DisallowConcurrentExecution
public class QuartzDisallowConcurrentExecution extends AbstractQuartzJob
{
@Override
protected void doExecute(JobExecutionContext context, DeviceJob deviceJob) throws Exception
{
JobInvokeUtil.invokeMethod(deviceJob);
}
}

View File

@@ -0,0 +1,19 @@
package com.fastbee.data.quartz;
import com.fastbee.iot.domain.DeviceJob;
import org.quartz.JobExecutionContext;
/**
* 定时任务处理(允许并发执行)
*
* @author ruoyi
*
*/
public class QuartzJobExecution extends AbstractQuartzJob
{
@Override
protected void doExecute(JobExecutionContext context, DeviceJob deviceJob) throws Exception
{
JobInvokeUtil.invokeMethod(deviceJob);
}
}

View File

@@ -0,0 +1,105 @@
package com.fastbee.data.quartz;
import com.fastbee.common.constant.ScheduleConstants;
import com.fastbee.common.exception.job.TaskException;
import com.fastbee.common.exception.job.TaskException.Code;
import com.fastbee.iot.domain.DeviceJob;
import org.quartz.*;
/**
* 定时任务工具类
*
* @author ruoyi
*
*/
public class ScheduleUtils
{
/**
* 得到quartz任务类
*
* @param deviceJob 执行计划
* @return 具体执行任务类
*/
private static Class<? extends Job> getQuartzJobClass(DeviceJob deviceJob)
{
boolean isConcurrent = "0".equals(deviceJob.getConcurrent());
return isConcurrent ? QuartzJobExecution.class : QuartzDisallowConcurrentExecution.class;
}
/**
* 构建任务触发对象
*/
public static TriggerKey getTriggerKey(Long jobId, String jobGroup)
{
return TriggerKey.triggerKey(ScheduleConstants.TASK_CLASS_NAME + jobId, jobGroup);
}
/**
* 构建任务键对象
*/
public static JobKey getJobKey(Long jobId, String jobGroup)
{
return JobKey.jobKey(ScheduleConstants.TASK_CLASS_NAME + jobId, jobGroup);
}
/**
* 创建定时任务
*/
public static void createScheduleJob(Scheduler scheduler, DeviceJob job) throws SchedulerException, TaskException
{
Class<? extends Job> jobClass = getQuartzJobClass(job);
// 1.创建任务
Long jobId = job.getJobId();
String jobGroup = job.getJobGroup();
JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(getJobKey(jobId, jobGroup)).build();
// 表达式调度构建器
CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());
cronScheduleBuilder = handleCronScheduleMisfirePolicy(job, cronScheduleBuilder);
// 2.创建触发器, 按新的cronExpression表达式构建一个新的trigger
CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(getTriggerKey(jobId, jobGroup))
.withSchedule(cronScheduleBuilder).build();
// 放入参数,运行时的方法可以获取
jobDetail.getJobDataMap().put(ScheduleConstants.TASK_PROPERTIES, job);
// 判断是否存在
if (scheduler.checkExists(getJobKey(jobId, jobGroup)))
{
// 防止创建时存在数据问题 先移除,然后在执行创建操作
scheduler.deleteJob(getJobKey(jobId, jobGroup));
}
// 3.任务和触发器添加到调度器
scheduler.scheduleJob(jobDetail, trigger);
// 暂停任务
if (job.getStatus().equals(ScheduleConstants.Status.PAUSE.getValue()))
{
scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup));
}
}
/**
* 设置定时任务策略
*/
public static CronScheduleBuilder handleCronScheduleMisfirePolicy(DeviceJob job, CronScheduleBuilder cb)
throws TaskException
{
switch (job.getMisfirePolicy())
{
case ScheduleConstants.MISFIRE_DEFAULT:
return cb;
case ScheduleConstants.MISFIRE_IGNORE_MISFIRES:
return cb.withMisfireHandlingInstructionIgnoreMisfires();
case ScheduleConstants.MISFIRE_FIRE_AND_PROCEED:
return cb.withMisfireHandlingInstructionFireAndProceed();
case ScheduleConstants.MISFIRE_DO_NOTHING:
return cb.withMisfireHandlingInstructionDoNothing();
default:
throw new TaskException("The task misfire policy '" + job.getMisfirePolicy()
+ "' cannot be used in cron schedule tasks", Code.CONFIG_ERROR);
}
}
}

View File

@@ -0,0 +1,334 @@
package com.fastbee.data.service.impl;
import com.fastbee.common.constant.ScheduleConstants;
import com.fastbee.common.exception.job.TaskException;
import com.fastbee.iot.domain.DeviceJob;
import com.fastbee.iot.mapper.DeviceJobMapper;
import com.fastbee.iot.service.IDeviceJobService;
import com.fastbee.iot.service.IDeviceService;
import com.fastbee.iot.service.cache.IDeviceCache;
import com.fastbee.data.quartz.CronUtils;
import com.fastbee.data.quartz.ScheduleUtils;
import com.fastbee.quartz.domain.SysJob;
import com.fastbee.quartz.mapper.SysJobMapper;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobDataMap;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
/**
* 定时任务调度信息 服务层
*
* @author kerwincui
*/
@Service
@Slf4j
public class DeviceJobServiceImpl implements IDeviceJobService
{
@Autowired
private Scheduler scheduler;
@Autowired
private DeviceJobMapper jobMapper;
@Autowired
private SysJobMapper sysJobMapper;
/**
* 项目启动时,初始化定时器 主要是防止手动修改数据库导致未同步到定时任务处理不能手动修改数据库ID和任务组名否则会导致脏数据
*/
@PostConstruct
public void init() throws SchedulerException, TaskException
{
scheduler.clear();
// 设备定时任务
List<DeviceJob> jobList = jobMapper.selectJobAll();
for (DeviceJob deviceJob : jobList)
{
ScheduleUtils.createScheduleJob(scheduler, deviceJob);
}
// 系统定时任务
List<SysJob> sysJobList = sysJobMapper.selectJobAll();
for (SysJob job : sysJobList)
{
com.fastbee.quartz.util.ScheduleUtils.createScheduleJob(scheduler, job);
}
}
/**
* 获取quartz调度器的计划任务列表
*
* @param job 调度信息
* @return
*/
@Override
public List<DeviceJob> selectJobList(DeviceJob job)
{
return jobMapper.selectJobList(job);
}
/**
* 通过调度任务ID查询调度信息
*
* @param jobId 调度任务ID
* @return 调度任务对象信息
*/
@Override
public DeviceJob selectJobById(Long jobId)
{
return jobMapper.selectJobById(jobId);
}
/**
* 暂停任务
*
* @param job 调度信息
*/
@Override
@Transactional(rollbackFor = Exception.class)
public int pauseJob(DeviceJob job) throws SchedulerException
{
Long jobId = job.getJobId();
String jobGroup = job.getJobGroup();
job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
int rows = jobMapper.updateJob(job);
if (rows > 0)
{
scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup));
}
return rows;
}
/**
* 恢复任务
*
* @param job 调度信息
*/
@Override
@Transactional(rollbackFor = Exception.class)
public int resumeJob(DeviceJob job) throws SchedulerException
{
Long jobId = job.getJobId();
String jobGroup = job.getJobGroup();
job.setStatus(ScheduleConstants.Status.NORMAL.getValue());
int rows = jobMapper.updateJob(job);
if (rows > 0)
{
scheduler.resumeJob(ScheduleUtils.getJobKey(jobId, jobGroup));
}
return rows;
}
/**
* 删除任务后所对应的trigger也将被删除
*
* @param job 调度信息
*/
@Override
@Transactional(rollbackFor = Exception.class)
public int deleteJob(DeviceJob job) throws SchedulerException
{
Long jobId = job.getJobId();
String jobGroup = job.getJobGroup();
int rows = jobMapper.deleteJobById(jobId);
if (rows > 0)
{
scheduler.deleteJob(ScheduleUtils.getJobKey(jobId, jobGroup));
}
return rows;
}
/**
* 批量删除调度信息
*
* @param jobIds 需要删除的任务ID
* @return 结果
*/
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteJobByIds(Long[] jobIds) throws SchedulerException
{
for (Long jobId : jobIds)
{
DeviceJob job = jobMapper.selectJobById(jobId);
deleteJob(job);
}
}
/**
* 根据设备Ids批量删除调度信息
*
* @param deviceIds 需要删除数据的设备Ids
* @return 结果
*/
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteJobByDeviceIds(Long[] deviceIds) throws SchedulerException
{
// 查出所有job
List<DeviceJob> deviceJobs=jobMapper.selectShortJobListByDeviceIds(deviceIds);
// 批量删除job
int rows=jobMapper.deleteJobByDeviceIds(deviceIds);
// 批量删除调度器
for(DeviceJob job:deviceJobs){
scheduler.deleteJob(ScheduleUtils.getJobKey(job.getJobId(), job.getJobGroup()));
}
}
/**
* 根据告警Ids批量删除调度信息
*
* @param alertIds 需要删除数据的告警Ids
* @return 结果
*/
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteJobByAlertIds(Long[] alertIds) throws SchedulerException
{
// 查出所有job
List<DeviceJob> deviceJobs=jobMapper.selectShortJobListByAlertIds(alertIds);
// 批量删除job
int rows=jobMapper.deleteJobByAlertIds(alertIds);
// 批量删除调度器
for(DeviceJob job:deviceJobs){
scheduler.deleteJob(ScheduleUtils.getJobKey(job.getJobId(), job.getJobGroup()));
}
}
/**
* 根据场景联动Ids批量删除调度信息
*
* @param sceneIds 需要删除数据的场景Ids
* @return 结果
*/
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteJobBySceneIds(Long[] sceneIds) throws SchedulerException
{
// 查出所有job
List<DeviceJob> deviceJobs=jobMapper.selectShortJobListBySceneIds(sceneIds);
// 批量删除job
int rows=jobMapper.deleteJobBySceneIds(sceneIds);
// 批量删除调度器
for(DeviceJob job:deviceJobs){
scheduler.deleteJob(ScheduleUtils.getJobKey(job.getJobId(), job.getJobGroup()));
}
}
/**
* 任务调度状态修改
*
* @param job 调度信息
*/
@Override
@Transactional(rollbackFor = Exception.class)
public int changeStatus(DeviceJob job) throws SchedulerException
{
int rows = 0;
String status = job.getStatus();
if (ScheduleConstants.Status.NORMAL.getValue().equals(status))
{
rows = resumeJob(job);
}
else if (ScheduleConstants.Status.PAUSE.getValue().equals(status))
{
rows = pauseJob(job);
}
return rows;
}
/**
* 立即运行任务
*
* @param job 调度信息
*/
@Override
@Transactional(rollbackFor = Exception.class)
public void run(DeviceJob job) throws SchedulerException
{
Long jobId = job.getJobId();
String jobGroup = job.getJobGroup();
DeviceJob properties = selectJobById(job.getJobId());
// 参数
JobDataMap dataMap = new JobDataMap();
dataMap.put(ScheduleConstants.TASK_PROPERTIES, properties);
scheduler.triggerJob(ScheduleUtils.getJobKey(jobId, jobGroup), dataMap);
}
/**
* 新增任务
*
* @param deviceJob 调度信息 调度信息
*/
@Override
@Transactional(rollbackFor = Exception.class)
public int insertJob(DeviceJob deviceJob) throws SchedulerException, TaskException
{
int rows = jobMapper.insertJob(deviceJob);
if (rows > 0)
{
ScheduleUtils.createScheduleJob(scheduler, deviceJob);
}
return rows;
}
/**
* 更新任务的时间表达式
*
* @param deviceJob 调度信息
*/
@Override
@Transactional(rollbackFor = Exception.class)
public int updateJob(DeviceJob deviceJob) throws SchedulerException, TaskException
{
DeviceJob properties = selectJobById(deviceJob.getJobId());
int rows = jobMapper.updateJob(deviceJob);
if (rows > 0)
{
updateSchedulerJob(deviceJob, properties.getJobGroup());
}
return rows;
}
/**
* 更新任务
*
* @param deviceJob 任务对象
* @param jobGroup 任务组名
*/
public void updateSchedulerJob(DeviceJob deviceJob, String jobGroup) throws SchedulerException, TaskException
{
Long jobId = deviceJob.getJobId();
// 判断是否存在
JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup);
if (scheduler.checkExists(jobKey))
{
// 防止创建时存在数据问题 先移除,然后在执行创建操作
scheduler.deleteJob(jobKey);
}
ScheduleUtils.createScheduleJob(scheduler, deviceJob);
}
/**
* 校验cron表达式是否有效
*
* @param cronExpression 表达式
* @return 结果
*/
@Override
public boolean checkCronExpressionIsValid(String cronExpression)
{
return CronUtils.isValid(cronExpression);
}
}