def get_array_chart_boll(): """获取合约运行技术布林通道图""" from mantis.sg.fisher.stbase.futures import BarData from mantis.sg.fisher.stbase.array import ArrayManager product = request.values.get('product', 'futures') # 默认期货 symbol = request.values.get('symbol') strategy_id = request.values.get('strategy_id') cycle = request.values.get('cycle', 1, type=int) # k线周期 ,默认 1分钟 num = request.values.get('num', 100, type=int) # 策略选取的多少根k线 lasttime = request.values.get('lasttime') # 查询最近截止的时间,默认为当前时间 if lasttime: lasttime = parse(lasttime) else: lasttime = datetime.datetime.now() conn = instance.datasourceManager.get('mongodb').conn db = None if product == 'futures': name = 'Ctp_Bar_{}'.format(cycle) db = conn[name] coll = db[symbol] rs = coll.find({ 'datetime': { '$lte': lasttime } }).sort('datetime', -1).limit(num) rs = list(rs) rs.reverse() close = map(lambda _: _['close'], rs) date = map(lambda _: _['datetime'], rs) print close[-3:] if not close: return CR(result='').response am = ArrayManager().setCloseArray(close) up, down = am.boll(20, 2, array=True) mid = am.ma(20, array=True) fig, ax = plt.subplots(figsize=(24, 8)) # fig, ax = plt.subplots() # fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(15, 8)) ax.plot(date, up, label='up') ax.plot(date, down, label='down') ax.plot(date, mid, label='mid') ax.plot(date, close, marker='.', label='close') # ax.scatter(range(num),close,marker='.',label='close') ax.legend() ax.grid(True) # for index,_ in enumerate (close): # x,y = date[index], close[index] # t = ax.text( index,y, str(y), withdash=True) base64image = export_png_base64(fig) plt.cla() # ax.close() plt.close("all") return CR(result=base64image).response
def query_device_event(): '''查询设备运行事件''' """ - dev_type 设备类型 1: 室内主机 ,2:室内屏设备 ,3:室外机 , 4: 物业App - dev_id 设备编号 - room_id 房间号 (可选) - event 事件名称 - start 开始时间 - end 结束时间 ( 不提供则一天) """ dev_type = request.values.get('dev_type', type=int) dev_id = request.values.get('dev_id', '') room_id = request.values.get('room_id', '') event = request.values.get('event', '') start = request.values.get('start', 0) end = request.values.get('end', 0) if not end: end = start + 3600 * 24 start = datetime.datetime.fromtimestamp(float(start)) end = datetime.datetime.fromtimestamp(float(end)) colls = { SystemDeviceType.InnerBox: model.InnerBoxLog, SystemDeviceType.InnerScreen: model.InnerScreenLog, SystemDeviceType.OuterBox: model.OuterBoxLog, SystemDeviceType.PropCallApp: model.PropertyAppLog, SystemDeviceType.PropSentryApp: model.SentryAppLog, } dev_type = int(dev_type) if dev_type not in colls.keys(): return CR().response fields = dict() if room_id: fields['room_id'] = room_id if dev_id: fields['dev_id'] = dev_id if event: fields['event'] = event fields['start'] = start fields['end'] = end collCls = colls[dev_type] rs = collCls.find(**fields).sort('time', 1) result = [] for r in rs: result.append( dict(dev_id=r.id, event=r.event, time=str(r.time), content=r.content)) return CR(result=result).response
def remove_device_from_group(): """删除设备到组 """ user = g.user group_id = request.values.get('group_id') device_id = request.values.get('device_id') rel = model.DeviceGroupRelation.get(user_id=user.id, group_id=group_id, device_id=device_id) if not rel: return CR().response rel.delete() return CR().response
def set_device_fence(): """设置设备的围栏参数 """ user = g.user device_id = request.values.get('device_id') data = {} for k, v in request.args.items(): data[k] = v fence = model.Fence.get_or_new(device_id=device_id) object_assign(fence, data) if fence.type not in FenceType.ALL: return ErrorReturn(ErrorDefs.ParameterInvalid).response fence.index = int(fence.index) fence.enable = int(fence.enable) fence.cx = float(fence.cx) fence.cy = float(fence.cy) fence.radius = int(fence.radius) fence.x1 = float(fence.x1) fence.y1 = float(fence.y1) fence.x2 = float(fence.x2) fence.y2 = float(fence.y2) fence.alarm_type = int(fence.alarm_type) device = model.Device.get(device_id=device_id) main = instance.serviceManager.get('main') # 发送设置围栏命令 cmd = '' cc = main.getCommandController(device.device_type) if fence.type == FenceType.CIRCLE: cmd = cc.setCircleFence(fence.cx, fence.cy, fence.radius, fence.inout) if cmd: main.sendCommand(device_id, cmd) fence.save() return CR().response
def get_last_position_multi(): """查询多个设备最近的位置信息 """ user = g.user text = request.values.get('device_ids', '') if not text: return CR(result=[]).response device_ids = text.split(',') result = [] for device_id in device_ids: data = _get_last_position(device_id) # pos = model.Position() # object_assign(pos,data) result.append(data) # return CR(result=pos.__dict__).response return CR(result=result).response
def get_device_info(): """""" user = g.user device_id = request.values.get('device_id') rel = model.DeviceUserRelation.get(user_id=str(user.id), device_id=device_id) if not rel: # 设备不存在 return ErrorReturn(ErrorDefs.ObjectNotExist).response device = model.Device.get(device_id=device_id) result = dict(device_id=device_id, device_type=device.device_type, imei=device.imei, sim=device.sim, mobile=device.mobile, admin_mobile=device.admin_mobile, name=rel.device_name, image=rel.device_image, update_time=rel.update_time, is_share_device=rel.is_share_device, share_user_id=rel.share_user_id, share_device_link=rel.share_device_link, password=device.password, map_scale=rel.map_scale) if not result['password']: result['password'] = '' result['capacity'] = capacity.get_product_features(device.device_type) if not rel.device_name: result['name'] = device.name return CR(result=result).response
def cmd_position_now(): """立即定位, 这里要进行请求阀控 2018.10.21 禁止发送 lbs 定位请求,在实时监控过程中,gps信号okey的 情况下,请求lbs,导致轨迹漂移 """ user = g.user device_id = request.values.get('device_id') main = instance.serviceManager.get('main') device = model.Device.get(device_id=device_id) cc = main.getCommandController(device.device_type) #设备上一次发送立即定位命令的时间 # redis记录最近一次发送时间,直到key失效之前不能重复发送 # 保证大量的客户端不会对设备发送大量的立即定位命令 name = constants.DevicePositionRequestTimeKey.format(device_id) redis = instance.datasourceManager.get('redis').conn value = redis.get(name) if not value: cmd = cc.positionNowGps() cmd_send(device_id, cmd, online=True) # cmd = cc.positionNowLbs() # cmd_send(device_id, cmd, online=True) expire = main.getConfig().get('max_position_request_interval', 10) redis.set(name, timestamp_current(), expire) # cmd = cc.positionNowLbs() # main.sendCommand(device_id, cmd) # cmd = cc.positionNowGps() # main.sendCommand(device_id, cmd) return CR().response
def ctp_strategy_code_status_info(): """返回策略的合约代码运行参数信息""" strategy_id = request.values.get('strategy_id', '') code = request.values.get('code') cs = model.CodeSettings.get(strategy_id=strategy_id, code=code) return CR(result=cs.dict()).response
def init_outerbox(): """室外机登录""" ip = request.remote_addr.split(':')[-1] box = model.OuterBox.get(ip=ip) # 根据ip检查设备是否登记 if not box: return ErrorReturn(ErrorDefs.ObjectNotExist, u'室外主机未登记') box.login_time = timestamp_current() box.save() data = {} garden = model.HomeGarden.get(id='8888') data['propcenter_ip'] = garden.property_call_server data['stream_server_url'] = garden.stream_server_url innerbox_list = [] rs = model.InnerBox.find(garden_id=garden.id, building_id=box.building_id) for _ in rs: innerbox_list.append(dict(room_id=_.room_id, ip=_.ip)) sentry_list = [] rs = model.SentryApp.find(garden_id=garden.id) for _ in rs: sentry_list.append(dict(name=_.name, ip=_.ip)) data['innerbox_list'] = innerbox_list data['sentry_list'] = sentry_list result = data return CR(result=result)
def get_code_list(): date = request.values.get('date', '') strategy_id = request.values.get('strategy_id') if not strategy_id or not date: return ErrorReturn(ErrorDefs.ParameterInvalid).response date = parse(date) conn = instance.datasourceManager.get('mongodb').conn dbname = 'TradeFisher_{}-{}-{}'.format(date.year, date.month, date.day) db = conn[dbname] model.CodeSettings.__database__ = db model.CodePrice.__database__ = db model.CodePosition.__database__ = db result = [] for cs in model.CodeSettings.find(strategy_id=strategy_id): data = cs.dict() price = model.CodePrice.get(code=cs.code) if price: data['price'] = price.dict() data['price']['time'] = str(data['price']['time']) pos = model.CodePosition.get(strategy_id=strategy_id, code=cs.code) if pos: data['pos'] = pos.dict() result.append(data) return CR(result=result).response
def get_innerbox_list(): """查询室内机列表""" # auth = g.auth # token = request.values.get('token') type_ = request.values.get("type", type=int) ip = request.remote_addr.split(':')[-1] result = [] if type_ in SystemDeviceType.ValidatedList and type_ != SystemDeviceType.OuterBox: """室内发起获取园区所有室内机的请求""" rs = model.InnerBox.find() for r in rs: result.append(dict(ip=r.ip, room_id=r.room_id)) if type_ == SystemDeviceType.OuterBox: """室外机查询室内机""" # 判别是围墙机还是单元机 box = model.OuterBox.get(ip=ip) if not box: return ErrorReturn(ErrorDefs.ObjectNotExist, u'室外主机未登记') if box.type == 'A': # 围墙机,返回所有 rs = model.InnerBox.find() for r in rs: result.append(dict(ip=r.ip, room_id=r.room_id)) if box.type == 'B': # 单元机 ,返回本单元相关的室内主机 rs = model.InnerBox.find(building_id=box.building_id) for r in rs: result.append(dict(ip=r.ip, room_id=r.room_id)) return CR(result=result).response
def get_group_info(): """获取设备详情 """ user = g.user group_id = request.values.get('group_id') include_devices = request.values.get('include_devices',0,type = int) group = model.Group.get(_id=ObjectId(group_id), user_id=user.id) if not group: return ErrorReturn(ErrorDefs.ObjectNotExist).response result = group.dict() if include_devices: result['devices'] = [] rs = model.DeviceGroupRelation.collection().find( {'group_id': group_id }).sort([('order',pymongo.ASCENDING)]) for rel in list(rs): # device = model.Device.get(device_id = rel.device_id) devrel = model.DeviceUserRelation.get(user_id = user.id,device_id = rel['device_id']) if devrel: data = dict( device_id= devrel.device_id, device_type = devrel.device_type, name = devrel.device_name ) result['devices'].append(data) result['device_count'] = len(result['devices']) return CR(result=result).response
def create_cargo_address(): """查询本人创建的共享设备信息 支持 共享设备编号查询 或 设备编号查询 如果共享记录未创建则创建,并返回 """ user = g.user name = request.values.get('name') phone = request.values.get('phone') address_ = request.values.get('address', '') is_default = request.values.get('is_default', 0, type=int) if not name or not phone or not address_: return ErrorReturn(ErrorDefs.ParameterInvalid, u'必须提供联系人、手机号、收件地址').response if is_default: # 将其他记录设置为非默认 model.CargoAddress.collection().update_many( { 'user_id': user.id, 'is_default': 1 }, {'$set': { 'is_default': 0 }}) address = model.CargoAddress() address.user_id = user.id address.name = name address.phone = phone address.address = address_ address.is_default = is_default address.order = timestamp_current() address.update_time = timestamp_current() address.save() return CR(result=address.id).response
def strategy_logs_last(): strategy_id = request.values.get('strategy_id') start_time = request.values.get('start_time') start_time = parse(start_time) # messages = model.TradeMessageLog.collection().find({'strategy_id': strategy_id}).sort('issue_time', -1) # rs = model.TradeMessageLog.collection().find( {'issue_time':{'$gte',start_time}}).sort('issue_time',-1) rs = model.TradeMessageLog.collection().find({ 'strategy_id': strategy_id, 'issue_time': { '$gte': start_time } }).sort('issue_time', 1) # rs = model.TradeMessageLog.collection().find( {'strategy_id': strategy_id}).sort('issue_time',1) # rs = model.TradeMessageLog.find(strategy_id=strategy_id)[:10] # rs = model.TradeMessageLog.collection().find( {'strategy_id': strategy_id}) result = [] for r in rs: text = 'code:{} title:{} message:{}'.format(r['code'], r['title'], r['message']) result.append(text) print '-*' * 20 print result return CR(result=result).response
def update_share_device(): """更新共享设备信息""" user = g.user share_id = request.values.get('share_id') name = request.values.get('name') expire = request.values.get('expire') # 过期时间 password = request.values.get('password', '') user_limit = request.values.get('user_limit', 0, type=int) status = request.values.get('status', '') if status not in ('open', 'close'): return ErrorReturn(ErrorDefs.ParameterInvalid, u'提交参数错误').response link = model.SharedDeviceLink.get(user_id=user.id, _id=ObjectId(share_id)) if not link: return ErrorReturn(ErrorDefs.ObjectNotExist).response if not password: password = '' link.name = name link.expire_time = expire link.password = password.strip() link.user_limit = user_limit link.status = status link.save() return CR(result='').response
def report_device_event(): '''上报设备运行事件''' from dateutil.parser import parse import time dev_type = request.values.get('dev_type') dev_id = request.values.get('dev_id', '') event = request.values.get("event") time = request.values.get("time", time.time()) content = request.values.get("content") encode = request.values.get('encode', 'plain') time = datetime.datetime.fromtimestamp(float(time)) colls = { SystemDeviceType.InnerBox: model.InnerBoxLog, SystemDeviceType.InnerScreen: model.InnerScreenLog, SystemDeviceType.OuterBox: model.OuterBoxLog, SystemDeviceType.PropCallApp: model.PropertyAppLog, SystemDeviceType.PropSentryApp: model.SentryAppLog, } dev_type = int(dev_type) if dev_type not in colls.keys(): return CR().response fields = dict(name='', id=dev_id, os='', ver='', ip=request.remote_addr.split(':')[-1], time=time, event=event, sys_time=datetime.datetime.now(), content=content) if encode == 'json': jsondata = json.loads(content) fields.update(jsondata) collCls = colls[dev_type] doc = collCls() doc.assign(fields) doc.save() if event == 'emergency': processEmergency() return CR().response
def update_device(): user = g.user device_id = request.values.get('device_id') password = request.values.get('password') name = request.values.get('name') mobile = request.values.get('mobile') # 设备内置电话号码 admin_mobile = request.values.get('admin_mobile') # 管理人手机号 image = request.values.get('image') map_scale = request.values.get('map_scale', 0, type=int) device = model.Device.get(device_id=device_id) if not device: return ErrorReturn(ErrorDefs.ObjectNotExist).response # 检测设备是否已经添加了 rel = model.DeviceUserRelation.get(user_id=str(user.id), device_id=device_id) if not rel: # 设备不存在 return ErrorReturn(ErrorDefs.ObjectNotExist).response if name: rel.device_name = name # 仅修改用户设备名称,原始设备名称并不修改 if map_scale: rel.map_scale = map_scale # 保存设备当前的地图缩放级别 if rel.is_share_device: # 共享设备的话,用户只能修改名称 if name: rel.save() return CR().response if name or map_scale: rel.save() kwargs = {} if password: kwargs['password'] = password if mobile: kwargs['mobile'] = mobile if admin_mobile: kwargs['admin_mobile'] = admin_mobile if image: kwargs['image'] = image if kwargs: device.update(**kwargs) return CR().response
def list_contracts(): """ 列举所有已订阅的合约代码 :return: """ service = instance.serviceManager.get('main') symbols = service.getSymbols() return CR().assign(symbols).response
def add_device_into_group(): """添加设备到组 """ user = g.user group_id = request.values.get('group_id') device_id = request.values.get('device_id') rel = model.DeviceGroupRelation.get(user_id = user.id,group_id=group_id,device_id=device_id) if rel: return CR().response rel = model.DeviceGroupRelation() rel.group_id = group_id rel.device_id = device_id rel.user_id = user.id rel.update_time = timestamp_current() rel.order = timestamp_current() rel.save() return CR(result=rel.id).response
def subscribe(): """ 订阅指定的合约代码 :return: """ symbols = request.get_json() service = instance.serviceManager.get('main') service.subscribe(symbols) return CR().response
def get_last_position(): """查询设备最近的位置信息 """ user = g.user device_id = request.values.get('device_id') data = _get_last_position(device_id) pos = model.Position() object_assign(pos, data) # return CR(result=pos.__dict__).response return CR(result=data).response
def get_wxuser_info(): """查询微信用户信息""" user = g.user user_id = request.values.get('user_id') wxuser = model.WxUser.get(user_id=user_id) if not wxuser: wxuser = model.WxUser() wxuser.user_id = user.id return CR(result=wxuser.dict()).response
def remove_cargo_address(): """ """ user = g.user id = request.values.get('id') address = model.CargoAddress.get(_id=ObjectId(id)) if not address: return ErrorReturn(ErrorDefs.ObjectNotExist, u'对象不存在').response address.delete() return CR(result=address.id).response
def update_wxsystem_info(): """更新微信系统信息 , 一个微信账户可能在多台主机登录""" user = g.user props = request.values.to_dict() wxsys = model.WxSystemInfo.get_or_new(user_id=user.id) object_assign(wxsys, props) wxsys.open_id = g.auth.open_id wxsys.save() return CR().response
def get_device_fence(): """获得设备的围栏参数 """ user = g.user device_id = request.values.get('device_id') fence = model.Fence.get(device_id=device_id) if not fence: return ErrorReturn(ErrorDefs.ObjectNotExist).response result = fence.dict() return CR(result=result).response
def create_share_device_code(): """生成分享码 缓存中记录分享码生成时间 """ from mantis.BlueEarth import constants redis = instance.datasourceManager.get('redis').conn code = '1212' name = constants.DeviceShareCodeCreateTimeKey.format(code) redis.set(name, timestamp_current(), 3600) return CR(result=code).response
def remove_favorite(): """ """ user = g.user id = request.values.get('id') favorite = model.Favorite.get(_id=ObjectId(id)) if not favorite: return ErrorReturn(ErrorDefs.ObjectNotExist, u'对象不存在').response favorite.delete() return CR().response
def vision_image_upload(): """上传对讲影像""" service = instance.serviceManager.get('main') store_path = service.getConfig().get('image_store_path') f = request.files['file'] device_id = request.values.get('dev_id') # 设备硬件编号 box = model.InnerBox.get(ip=request.remote_addr.split(':')[-1]) if not box: return CR().response room_id = box.room_id fmt = '%Y-%m-%d_%H-%M-%S.mp4' timetick = time.strftime(fmt, time.localtime()) store_path = os.path.join(store_path, room_id) if not os.path.exists(store_path): os.makedirs(store_path) store_path = os.path.join(store_path, timetick) f.save(store_path) return CR().response
def update_wxuser_info(): """更新微信用户信息""" user = g.user wxuser = model.WxUser.get_or_new(user_id=user.id) props = request.values.to_dict() object_assign(wxuser, props) wxuser.user_id = user.id wxuser.open_id = g.auth.open_id wxuser.save() return CR().response
def ctp_strategy_stop(): """停止策略运行""" strategy_id = request.values.get("strategy_id", '') main = instance.serviceManager.get("main") locust_dir = main.getConfig().get('locust_home') path = os.path.join(locust_dir, 'scripts/st-stop.sh') cmd = 'bash {} {} '.format(path, strategy_id) print 'System Exec:', cmd os.system(cmd) return CR().response