Exemplo n.º 1
0
 def post(self):
     taskName = self.get_argument('taskName', '')
     taskTopic = self.get_argument('taskTopic', '')
     # base64编码的消息内容
     taskMsg = self.get_argument('taskMsg', '')
     # 定时时间
     run_date = self.get_argument('run_date', '')
     sn = self.get_argument('sn', None)
     if not taskName or not taskTopic or not taskMsg or not sn:
         self.write(JsonError('参数错误'))
         self.finish()
     else:
         # alarm_time = run_date.strftime('%Y-%m-%d %H:%M:%S')
         payload = taskMsg.split(' ')
         ack = bytearray()
         ack.extend(map(hexTrans, payload))
         print payload
         try:
             task = scheduler.add_job(addSendMsg,
                                      'date',
                                      run_date=run_date,
                                      args=[taskTopic, ack])
             # 任务存入数据库  时间可以以str形式 也可以格式化为 datetime对象后再存入 datetime.strptime(run_date,'%Y-%m-%d %H:%M:%S')
             res = yield self.addonceTask('hpy_' + task.id, taskName,
                                          taskTopic, taskMsg, run_date, sn)
             self.write(JsonResponse('hpy_' + task.id))
             self.finish()
         except Exception as e:
             print e
             self.write(JsonResponse(e.__str__()))
             self.finish()
Exemplo n.º 2
0
 def get(self):
     self.make_sure_mysql_usable()
     token = self.get_argument('token', None)
     try:
         uc = UserControl.objects.get(token=token)
         if not uc.headerImage:
             self.write(JsonResponse('nothing'))
         else:
             self.write(JsonResponse(uc.headerImage))
     except UserControl.DoesNotExist:
         self.write(JsonError('need login in'))
Exemplo n.º 3
0
 def post(self):
     taskName = self.get_argument('taskName', '')
     taskTopic = self.get_argument('taskTopic', '')
     # base64编码的消息内容
     taskMsg = self.get_argument('taskMsg', '')
     # Cron时间
     year = self.get_argument('year', '*')  # (int|str) – 4-digit year
     month = self.get_argument('month', '*')  # (int|str) – month (1-12)
     day = self.get_argument('day', '*')  # day of the (1-31)
     week = self.get_argument('week', '*')  # (int|str) – ISO week (1-53)
     day_of_week = self.get_argument(
         'day_of_week', '*'
     )  # number or name of weekday (0-6 or mon,tue,wed,thu,fri,sat,sun)
     hour = self.get_argument('hour', '*')  # (int|str) – hour (0-23)
     minute = self.get_argument('minute', '*')  # (int|str) – minute (0-59)
     second = self.get_argument('second', '*')  # (int|str) – second (0-59)
     start_date = self.get_argument('start_date',
                                    None)  # 起始时间 需要转成 str 类型  或 NoneType
     end_date = self.get_argument('end_date',
                                  None)  # 结束时间 需要转成 str 类型  或 NoneType
     sn = self.get_argument('sn', None)
     if not taskName or not taskTopic or not taskMsg or not sn:
         self.write(JsonError('参数错误'))
         self.finish()
     else:
         payload = taskMsg.split(' ')
         ack = bytearray()
         ack.extend(map(hexTrans, payload))
         print payload
         try:
             task = scheduler.add_job(addSendMsg,
                                      'cron',
                                      year=year,
                                      month=month,
                                      day=day,
                                      week=week,
                                      day_of_week=day_of_week,
                                      hour=hour,
                                      minute=minute,
                                      second=second,
                                      start_date=start_date,
                                      end_date=end_date,
                                      args=[taskTopic, ack])
             res = yield self.addCronTask('hpy_' + task.id, sn, taskName,
                                          taskTopic, taskMsg, year, month,
                                          day, week, day_of_week, hour,
                                          minute, second, start_date,
                                          end_date)
             self.write(JsonResponse('hpy_' + task.id))
             self.finish()
         except Exception as e:
             print e
             self.write(JsonResponse(e.__str__()))
             self.finish()
Exemplo n.º 4
0
 def get(self, sn):
     sn = sn.upper()
     queryTime = datetime.datetime.utcnow()
     billHistory = []
     starttime = datetime.datetime(queryTime.year, 1, 1, 0, 0, 0)
     cursor = self.db.data_month.find(
         {
             'sn': sn,
             'postTime': {
                 "$lte": queryTime
             },
             'postTime': {
                 "$gte": starttime
             }
         },
         sort=[('postTime', 1)])
     for document in (yield cursor.to_list(length=100)):
         pprint.pprint(document)
         billMonth = {}
         postTime = document["postTime"]
         billMonth["month"] = postTime.month
         billMonth["power"] = document["power"]
         billHistory.append(billMonth)
     self.write(JsonResponse(billHistory))
     self.finish()
Exemplo n.º 5
0
 def get(self, token):
     self.make_sure_mysql_usable()
     try:
         uc = UserControl.objects.get(token=token)
         uc.refreshToken()
         uc.save()
         self.write(JsonResponse('quit'))
     except Exception as e:
         self.write(JsonError('token_invalid'))
Exemplo n.º 6
0
 def post(self):
     job = str(self.get_argument('job', ''))
     type = self.get_argument('type', '')
     task_name = self.get_argument('taskName', '')
     task_topic = self.get_argument('taskTopic', '')
     task_msg = self.get_argument('taskMsg', '')
     run_date = self.get_argument('run_date', '')
     sn = self.get_argument('sn', '')
     status = self.get_argument('status', '')
     if not job or not type or not task_name or not task_topic or not task_msg or not run_date or not sn or not status:
         self.write(JsonError('参数错误'))
         self.finish()
     else:
         #remove first
         splStr = job.split('_')
         jobid = splStr[1]
         try:
             scheduler.remove_job(jobid)
             res = yield self.removeTask(job, type)
         except Exception as e:
             print e
             self.write(JsonResponse(e.__str__()))
             self.finish()
             return
         #add again
         payload = task_msg.split(' ')
         ack = bytearray()
         ack.extend(map(hexTrans, payload))
         print payload
         try:
             task = scheduler.add_job(addSendMsg,
                                      'date',
                                      run_date=run_date,
                                      args=[task_topic, ack])
             # 任务存入数据库  时间可以以str形式 也可以格式化为 datetime对象后再存入 datetime.strptime(run_date,'%Y-%m-%d %H:%M:%S')
             res = yield self.addonceTask('hpy_' + task.id, task_name,
                                          task_topic, task_msg, run_date,
                                          sn, 1)
             self.write(JsonResponse('hpy_' + task.id))
             self.finish()
         except Exception as e:
             print e
             self.write(JsonResponse(e.__str__()))
             self.finish()
Exemplo n.º 7
0
 def post(self):
     userEmail = self.get_argument('email', None)
     if userEmail is not None:
         code = random.randint(100000, 999999)
         sendMail.delay(userEmail, str(code))
         r = redis.Redis(connection_pool=self.redisPool)
         r.set(userEmail, code, ex=600)  # expire 6 min
         self.write(JsonResponse("success"))
     else:
         self.write(JsonError("no email input"))
Exemplo n.º 8
0
 def get(self):
     sn = self.get_argument('sn', None)
     if sn is None:
         self.write(JsonError('参数错误'))
         self.finish()
     else:
         sn = sn.upper()
         res = yield self.getTasks(sn)
         self.write(JsonResponse(res))
         self.finish()
Exemplo n.º 9
0
 def get(self):
     job = self.get_argument('job', '')
     type = self.get_argument('type', '')
     if not job or not type:
         self.write(JsonError(u'无参数'))
         self.finish()
     else:
         splStr = job.split('_')
         jobid = splStr[1]
         try:
             conn = rpyc.connect('localhost', 12345)
             conn.root.remove_job(jobid)
             yield self.removeTask(job, type)
             self.write(JsonResponse(job))
         except Exception as e:
             print e
             self.write(JsonResponse(e.__str__()))
         finally:
             conn.close()
             self.finish()
Exemplo n.º 10
0
 def post(self):
     token = self.get_argument('token', None)
     newName = self.get_argument('newName', None)
     try:
         user = UserControl.objects.get(token=token)
         user.user_name = newName
         user.save()
         self.write(JsonResponse({'name': newName}))
     except Exception as e:
         print e
         self.write(JsonError('chane new name failed'))
Exemplo n.º 11
0
 def get(self, token):
     self.make_sure_mysql_usable()
     try:
         devices = Device.objects.filter(user__token=token).all()
         lists = []
         if not devices:
             self.write(JsonResponse(lists))
         else:
             for device in devices:
                 lists.append({
                     'sn': device.sn,
                     'name': device.name,
                     'type': device.type,
                     'address': device.address,
                     'controlPass': device.controlPass
                 })
             self.write(JsonResponse(lists))
     except Exception as e:
         print e
         self.write(JsonError('ERROR.' + e.__str__()))
Exemplo n.º 12
0
 def get(self, zigbee_sn):
     zigbee_sn = zigbee_sn.upper()
     result1 = yield self.db.data_all.distinct('device_sn',
                                               {'zigbee_sn': zigbee_sn})
     result2 = yield self.db.data_hour.distinct('device_sn',
                                                {'zigbee_sn': zigbee_sn})
     set1 = set(result1)
     set2 = set(result2)
     set3 = set1 | set2
     listResult = list(set3)
     self.write(JsonResponse(listResult))
     self.finish()
Exemplo n.º 13
0
 def post(self):
     self.make_sure_mysql_usable()
     sn = self.get_argument('sn', None)
     if sn is not None:
         sn = sn.upper()
     token = self.get_argument('token', None)
     try:
         uc = UserControl.objects.get(token=token)
         device = Device.objects.get(sn=sn)
         uc.device_set.add(device)
         dc = deviceControl.objects.filter(device=device, user=uc)
         if not dc:
             dc = deviceControl(device=device, user=uc, right=2)
             dc.save()
         return self.write(JsonResponse('device_add_success'))
     except Device.DoesNotExist:
         device = Device.objects.create(type='1', sn=sn)
         uc.device_set.add(device)
         dc = deviceControl(device=device, user=uc, right=1)
         dc.save()
         self.write(JsonResponse('device_add_success'))
     except Exception as e:
         print e
         self.write(JsonError('device_add_fail'))
Exemplo n.º 14
0
    def get(self, device_sn):
        fromDate = self.get_argument('from', None)
        toDate = self.get_argument('to', None)
        startTime = None
        endTime = None
        if fromDate is not None:
            temp = time.strptime(fromDate, "%Y-%m-%d")
            y, m, d = temp[0:3]
            startTime = datetime.datetime(y, m, d)
            if toDate is not None:
                temp = time.strptime(toDate, "%Y-%m-%d")
                y, m, d = temp[0:3]
                endTime = datetime.datetime(y, m, d)
            else:
                temp = datetime.datetime.now()
                endTime = datetime.datetime(temp.year, temp.month, temp.day)
        else:
            temp = datetime.datetime.now()
            startTime = datetime.datetime(temp.year, temp.month, temp.day)
            endTime = datetime.datetime(temp.year, temp.month, temp.day)
        print startTime
        print endTime

        result = []
        cursor = self.db.data_hour.find(
            {
                'device_sn': device_sn,
                'dayTime': {
                    '$gte': startTime,
                    '$lte': endTime
                }
            },
            sort=[('dayTime', 1)])
        for document in (yield cursor.to_list(length=100)):
            print document.__str__
            day = {}
            for k, v in document.items():
                print k
                if k == '_id':
                    continue
                elif k == 'dayTime':
                    day[k] = document[k].strftime("%Y-%m-%d")
                else:
                    day[k] = v
            result.append(day)
        self.write(JsonResponse(result))
        self.finish()
Exemplo n.º 15
0
 def get(self):
     job = self.get_argument('job', '')
     type = self.get_argument('type', '')
     if not job or not type:
         self.write(JsonError(u'无参数'))
         self.finish()
     else:
         splStr = job.split('_')
         jobid = splStr[1]
         try:
             scheduler.remove_job(jobid)
         except Exception as e:
             print e
         finally:
             res = yield self.removeTask(job, type)
             self.write(JsonResponse(job))
             self.finish()
Exemplo n.º 16
0
 def post(self):
     self.make_sure_mysql_usable()
     sn = self.get_argument('sn', '')
     if sn != '':
         sn = sn.upper()
     token = self.get_argument('token', '')
     try:
         uc = UserControl.objects.get(token=token)
         device = Device.objects.get(sn=sn)
         dc = deviceControl.objects.get(device=device, user=uc)
         if not dc:
             self.write(JsonError('权限查询失败'))
         else:
             right = dc.right
             self.write(JsonResponse({'right': right}))
     except Exception as e:
         print e
         self.write(JsonError('权限查询失败'))
Exemplo n.º 17
0
 def post(self):
     self.make_sure_mysql_usable()
     sn = self.get_argument('sn', None)
     if sn is not None:
         sn = sn.upper()
     token = self.get_argument('token', None)
     try:
         uc = UserControl.objects.get(token=token)
         device = Device.objects.get(sn=sn)
         uc.device_set.remove(device)
         users = UserControl.objects.filter(device__sn=sn)
         if not users:
             device.delete()
         return self.write(JsonResponse('unbind_device_success'))
     except Device.DoesNotExist:
         self.write(JsonError('unbind_device_success'))
     except Exception as e:
         print e
         self.write(JsonError('unbind_device_fail'))
Exemplo n.º 18
0
 def get(self, sn):
     sn = sn.upper()
     queryTime = datetime.datetime.utcnow()
     currentMonth = queryTime.month
     print queryTime
     print currentMonth
     billMonth = {}
     starttime = datetime.datetime(queryTime.year, currentMonth, 1, 0, 0, 0)
     result_first = yield self.db.data_hour.find_one(
         {
             'sn': sn,
             'type': 'power',
             'postTime': {
                 "$lte": queryTime
             },
             'postTime': {
                 "$gte": starttime
             }
         },
         sort=[('postTime', 1)])
     result_last = yield self.db.data_hour.find_one(
         {
             'sn': sn,
             'type': 'power',
             'postTime': {
                 "$lte": queryTime
             },
             'postTime': {
                 "$gte": starttime
             }
         },
         sort=[('postTime', -1)])
     if (result_first != None):
         consumeMonth = result_last["WpP"] - result_first["WpP"]
     else:
         consumeMonth = 0
     billMonth["power"] = consumeMonth
     billMonth["month"] = currentMonth
     billMonth["sn"] = sn
     self.write(JsonResponse(billMonth))
     self.finish()
Exemplo n.º 19
0
 def post(self):
     filesList = self.request.files.items()
     uploadFile = filesList[0]
     info = uploadFile[1][0]
     filename, content_type = info['filename'], info['content_type']
     body = info['body']
     print('POST "%s" "%s" %d bytes', filename, content_type, len(body))
     self.make_sure_mysql_usable()
     token = self.get_argument('token', None)
     try:
         uc = UserControl.objects.get(token=token)
         uc.headerImage = filename
         uc.save()
         with open(os.path.join(UPLOAD_IMAGE_PATH, filename),
                   'wb') as up:  # os拼接文件保存路径,以字节码模式打开
             up.write(body)  # 将文件写入到保存路径目录
         self.write(JsonResponse(filename))
     except UserControl.DoesNotExist:
         self.write(JsonError('need login in'))
     except Exception as e:
         self.write(JsonError(e.__str__()))
Exemplo n.º 20
0
 def get(self, device_sn):
     device_sn = device_sn.lower()
     currentTime = datetime.datetime.now()
     year = self.get_argument('year', currentTime.year)
     yearTime = datetime.datetime(int(year), 1, 1)
     result = yield self.db.data_month.find_one({
         'device_sn': device_sn,
         'year': yearTime
     })
     monthHis = {}
     if result is not None:
         for k, v in result.items():
             print k
             if k == '_id':
                 continue
             elif k == 'year':
                 monthHis[k] = result[k].strftime("%Y")
             else:
                 monthHis[k] = v
     self.write(JsonResponse(monthHis))
     self.finish()
Exemplo n.º 21
0
 def post(self):
     try:
         self.make_sure_mysql_usable()
         param = self.request.body.decode('utf-8')
         print self.get_argument('password', '')
         print self.get_argument('username', '')
         password = self.get_argument('password', None)
         username = self.get_argument('username',
                                      None)  #phone number for now
         if username is None:
             self.write(JsonError('login_user_name_error'))
         if password is None:
             self.write(JsonError('password_empty'))
         if isMobilePhone(username):
             uc = UserControl.objects.get(
                 phone=username,
                 password=hashlib.md5('hpy:' + password).hexdigest())
         elif isEmail(username):
             uc = UserControl.objects.get(
                 email=username,
                 password=hashlib.md5('hpy:' + password).hexdigest())
         else:
             self.write(JsonError('user_name_error'))
             return
         if not uc.user_name:
             userName = ''
         else:
             userName = uc.user_name
         self.write(
             JsonResponse({
                 'msg': 'success',
                 'token': uc.token,
                 'username': userName
             }))
     except UserControl.DoesNotExist:
         self.write(JsonError('no_user'))
     except Exception as e:
         print e
         self.write(JsonError('login_failed'))
Exemplo n.º 22
0
 def post(self):
     self.make_sure_mysql_usable()
     name = self.get_argument('name', '')
     address = self.get_argument('address', '')
     controlPass = self.get_argument('controlPass', '')
     sn = self.get_argument('sn', None)
     if sn is not None:
         sn = sn.upper()
     token = self.get_argument('token', None)
     try:
         uc = UserControl.objects.get(token=token)
         device = Device.objects.get(sn=sn)
         dc = deviceControl.objects.get(device=device, user=uc)
         #if dc.right == 2:
         #    self.write(JsonError('无设备信息更新权限'))
         #else:
         device.name = name
         device.address = address
         device.controlPass = controlPass
         device.save()
         self.write(JsonResponse('update_device_info_success'))
     except Exception as e:
         print e
         self.write(JsonError('update_device_info_fail'))
Exemplo n.º 23
0
 def post(self):
     """忘记密码 通过手机验证修改密码
        post  {'phone': '18767100996', 'code': code, 'newPWD': 'xxxx'}
     """
     self.make_sure_mysql_usable()
     newPass = self.get_argument('newPass', None)
     phone = self.get_argument('phone', None)  #接口更新,这个phone可以是手机号码或者邮箱
     code = self.get_argument('code', None)
     r = redis.Redis(connection_pool=self.redisPool)
     smsCode = r.get(phone)
     print smsCode
     if not smsCode:
         self.write(JsonError('code_wrong'))
     elif phone and code and newPass:
         if int(code) == int(smsCode):
             try:
                 if isMobilePhone(phone):
                     user = UserControl.objects.get(phone=phone)
                 elif isEmail(phone):
                     user = UserControl.objects.get(email=phone)
                 user.set_password(newPass)
                 user.refreshToken()  # 刷新token
                 user.save()
                 self.write(JsonResponse(user.token))
             except UserControl.DoesNotExist:
                 self.write(JsonError('no_user'))
             except IntegrityError as e:
                 print e
                 self.write(JsonError('password_change_fail'))
             except Exception as e:
                 print e
                 self.write(JsonError('password_change_fail'))
         else:
             self.write(JsonError('code_wrong'))
     else:
         self.write(JsonError('wrong_parameters'))
Exemplo n.º 24
0
 def get(self, device_sn):
     res = yield self.getRealData(device_sn)
     self.write(JsonResponse(res))
     self.finish()
Exemplo n.º 25
0
    def post(self):
        self.make_sure_mysql_usable()
        password = self.get_argument('password', None)
        username = self.get_argument('username', None)  # phone number for now
        print username
        code = self.get_argument('code', None)
        r = redis.Redis(connection_pool=self.redisPool)
        smsCode = r.get(username)
        if smsCode is None:
            self.write(JsonError('code_expire'))
        elif int(code) == int(smsCode):
            #register when verification code in valid
            if isMobilePhone(username):
                if UserControl.objects.filter(phone=username).exists():
                    self.write(JsonError('user_exist'))
                else:
                    user = UserControl(phone=username, user_name=username)
                    user.set_password(password)
                    # 首次写入token令牌
                    user.refreshToken()
                    try:
                        user.save()
                        result = {
                            'msg':
                            'register_success',
                            'user_id':
                            user.pk,
                            'token':
                            user.token,
                            'token_refresh_at':
                            user.token_refresh_at.strftime('%Y-%m-%d %H:%M:%S')
                        }
                        self.write(JsonResponse(result))
                    except IntegrityError:
                        self.write(JsonError('register_fail'))
                    except Exception as e:
                        print e
                        self.write(JsonError('register_fail'))

            elif isEmail(username):
                if UserControl.objects.filter(email=username).exists():
                    self.write(JsonError('user_exist'))
                else:
                    user = UserControl(email=username, user_name=username)
                    user.set_password(password)
                    # 首次写入token令牌
                    user.refreshToken()
                    try:
                        user.save()
                        result = {
                            'msg':
                            'register_success',
                            'user_id':
                            user.pk,
                            'token':
                            user.token,
                            'token_refresh_at':
                            user.token_refresh_at.strftime('%Y-%m-%d %H:%M:%S')
                        }
                        self.write(JsonResponse(result))
                    except IntegrityError:
                        self.write(JsonError('register_fail'))
                    except Exception as e:
                        print e
                        self.write(JsonError('register_fail'))
        else:
            self.write(JsonError('code_wrong'))
Exemplo n.º 26
0
 def get(self, phone):
     res = yield self.background_task(phone)
     response = eval(res)
     self.write(JsonResponse({'msg': response['Message']}))