def genMsgForDevs(): okDev=[] errorInfo=[] nt=datetime.datetime.now() now=("%s"%(nt))[:19] # last=("%s"%(nt-datetime.timedelta(0,2*24*60*60)))[:19] #两天前 # for device in iclock.objects.exclude(DelTag=1).exclude(State=DEV_STATUS_PAUSE).exclude(LastActivity__lt=last): for sc in IclockMsg.objects.filter(StartTime__lt=now):#.exclude(EndTime__lt=last): device=sc.Device() try: start = ("%s"%sc.StartTime)[:19] diff = timeDiffMin(sc.EndTime, sc.StartTime) if not sc.EndTime or sc.EndTime>nt: ##没有结束时间,或结束时间还没有到,进行正常发送信息服务 if sc.MsgType==M_WEATHER: # weather forecast checkWeatherForDev(device) elif sc.MsgType in (M_NEWS, M_SYS_NOTES): checkNewsForDev(device, sc.MsgType, sc.MsgParam, now, start, diff, sc.LastTime) elif (sc.MsgType in (M_DEPT_NOTES, M_DEPT_SMS)) and not sc.LastTime: checkNewsForDev(device, sc.MsgType, sc.MsgParam, now, start, diff) elif (sc.MsgType in [M_PRIV_SMS, ]) and not sc.LastTime: appendDevCmd(device, "SMS TAG=0x%X\tUID=%s\tMIN=%s\tStartTime=%s\tMSG=%s"%(0xFE, sc.MsgParam, diff, start, sc.MsgContent)) elif (sc.LastTime and sc.LastTime<sc.EndTime): #已到结束时间,并且还没有处理结束工作 #进行结束定制信息的处理 pass sc.LastTime=now sc.save() okDev.append("%s"%device) except Exception, e: errorInfo.append("Error To Service messeges for %s: %s"%(device, e))
def genMsgForDevs(): okDev = [] errorInfo = [] nt = datetime.datetime.now() now = ('%s' % nt)[:19] last = ('%s' % (nt - datetime.timedelta(0, 172800)))[:19] for sc in IclockMsg.objects.filter(StartTime__lt=now): device = sc.Device() try: start = ('%s' % sc.StartTime)[:19] diff = timeDiffMin(sc.EndTime, sc.StartTime) if not sc.EndTime or sc.EndTime > nt: if sc.MsgType == M_WEATHER: checkWeatherForDev(device) elif sc.MsgType in (M_NEWS, M_SYS_NOTES): checkNewsForDev(device, sc.MsgType, sc.MsgParam, now, start, diff, sc.LastTime) elif sc.MsgType in (M_DEPT_NOTES, M_DEPT_SMS) and not sc.LastTime: checkNewsForDev(device, sc.MsgType, sc.MsgParam, now, start, diff) elif sc.MsgType in [M_PRIV_SMS] and not sc.LastTime: appendDevCmd( device, 'SMS TAG=0x%X\tUID=%s\tMIN=%s\tStartTime=%s\tMSG=%s' % (254, sc.MsgParam, diff, start, sc.MsgContent)) else: if sc.LastTime and sc.LastTime < sc.EndTime: pass sc.LastTime = now sc.save() okDev.append('%s' % device) except Exception, e: errorInfo.append('Error To Service messeges for %s: %s' % (device, e))
def checkNewsForDev(device, type, param, now, start, mins, LastTime=None): for info in messages.objects.filter(StartTime__lt=now): if info.EndTime and info.EndTime<now: continue msg=info.MsgContent if type in [M_DEPT_NOTES, M_DEPT_SMS]: #检查并发送属于本部门的信息 if not (not device.DeptID_id or (device.DeptID_id==info.DeptID_id)): msg="" elif LastTime and info.StartTime<=LastTime: msg="" if msg: appendDevCmd(device, "SMS TAG=0x%X\tUID=1\tMIN=%s\tStartTime=%s\tMSG=%s"%(0xFD, mins, start, lcdMsg(msg)))
def checkDevice(request, response): #by super 2010-08-26 增加push sdk协议字段 pushver = 0.0 if request.REQUEST.has_key('pushver'): try:pushver = float(request.REQUEST["pushver"]) except:pass try: sn = request.REQUEST["SN"] except: sn = request.META["QUERY_STRING"] sn = (sn + "SN=").split("SN=")[1].split("&")[0] if sn == "": errorLog(request) response.write("UNKNOWN Device") return None try: device = getDevice(sn) #by super 2010-08-26 增加push sdk协议字段,更新协议版本 if float(device.PushVersion) != pushver: device.PushVersion = pushver device.save() if device.DelTag: if settings.ICLOCK_AUTO_REG: device.DelTag = None device.save() else: return None if device.State == DEV_STATUS_PAUSE: return None except: if len(sn) >= 6 and settings.ICLOCK_AUTO_REG and not request.REQUEST.has_key('PIN'): #若SN正确,设置可以自动注册,且没有查询用户信息的话,注册该考勤机 device = iclock(SN=sn, Alias=request.META["REMOTE_ADDR"], LastActivity=datetime.datetime.now(), IPAddress=request.META["REMOTE_ADDR"], DeptID=getDefaultDept()) #by super 2010-08-26 增加push sdk协议字段 device.PushVersion = pushver device.save() device = iclock.objects.get(SN=sn) appendDevCmd(device, "INFO") appendDevCmd(device, "CHECK") else: errorLog(request) response.write("UNKNOWN Device: " + sn) return None return device
def checkNewsForDev(device, type, param, now, start, mins, LastTime=None): for info in messages.objects.filter(StartTime__lt=now): if info.EndTime: if info.EndTime < now: continue msg = info.MsgContent if type in [M_DEPT_NOTES, M_DEPT_SMS]: msg = not device.DeptID_id or device.DeptID_id == info.DeptID_id or '' else: if LastTime and info.StartTime <= LastTime: msg = '' if msg: appendDevCmd( device, 'SMS TAG=0x%X\tUID=1\tMIN=%s\tStartTime=%s\tMSG=%s' % (253, mins, start, lcdMsg(msg)))
def checkDevice(request, response): pushver = 0.0 if request.REQUEST.has_key('pushver'): try: pushver = float(request.REQUEST['pushver']) except: pass try: sn = request.REQUEST['SN'] except: sn = request.META['QUERY_STRING'] sn = (sn + 'SN=').split('SN=')[1].split('&')[0] if sn == '': errorLog(request) response.write('UNKNOWN Device') return else: try: device = getDevice(sn) if float(device.PushVersion) != pushver: device.PushVersion = pushver device.save() if device.DelTag: if settings.ICLOCK_AUTO_REG: device.DelTag = None device.save() else: return if device.State == DEV_STATUS_PAUSE: return except: if len(sn) >= 6 and settings.ICLOCK_AUTO_REG and not request.REQUEST.has_key('PIN'): device = iclock(SN=sn, Alias=request.META['REMOTE_ADDR'], LastActivity=datetime.datetime.now(), IPAddress=request.META['REMOTE_ADDR'], DeptID=getDefaultDept()) device.PushVersion = pushver device.save() device = iclock.objects.get(SN=sn) appendDevCmd(device, 'INFO') appendDevCmd(device, 'CHECK') else: errorLog(request) response.write('UNKNOWN Device: ' + sn) return return device
def checkWeatherForDev(device): areaID = device.City if not areaID: return None datas = getWeather(areaID) if datas and (u"NULL\n" not in datas): cmd = getWeatherCmd(device, datas) if cmd: return appendDevCmd(device, cmd) return datas
def checkWeatherForDev(device): areaID=device.City if not areaID: return None datas=getWeather(areaID) if datas and (u"NULL\n" not in datas): cmd=getWeatherCmd(device, datas) if cmd: return appendDevCmd(device, cmd) return datas
def checkUpgradeFW(cmdobj, request): appendDevCmd(cmdobj.SN, 'REBOOT') if cmdobj.CmdContent.find('PutFile file/fw/') == 0 and cmdobj.CmdContent.find('main.gz') > 0: settings.UPDATE_COUNT -= 1 url, fname = getFW(cmdobj.SN) diff = int(cmdobj.CmdReturn) - os.path.getsize(fname) if diff in (0, 1): if cmdobj.CmdContent.find('main.gz.tmp') > 0: appendDevCmd(cmdobj.SN, 'Shell mv main.gz.tmp /mnt/mtdblock/main.gz') appendDevCmd(cmdobj.SN, 'REBOOT') else: appendDevCmd(cmdobj.SN, cmdobj.CmdContent)
def checkUpgradeFW(cmdobj, request): appendDevCmd(cmdobj.SN, "REBOOT")#add by liupan,2011-12-01 if cmdobj.CmdContent.find("PutFile file/fw/") == 0 and cmdobj.CmdContent.find("main.gz") > 0: #upgrade firmware settings.UPDATE_COUNT -= 1 url, fname = getFW(cmdobj.SN) diff = int(cmdobj.CmdReturn) - os.path.getsize(fname) #返回的文件字节数和实际的文件字节数比较 if diff in [0, 1]: #升级成功, 有一旧版本的固件下载文件后会多出一个字节 # if cmdobj.SN.OEMVendor !="ZKSoftware Inc.": appendDevCmd(cmdobj.SN, "SET OPTION ~OEMVendor ZKSoftware Inc.") if cmdobj.CmdContent.find("main.gz.tmp") > 0: appendDevCmd(cmdobj.SN, "Shell mv main.gz.tmp /mnt/mtdblock/main.gz") # if hostIsOld(request): # appendDevCmd(cmdobj.SN, "SET OPTION WebServerIP 10.33.109.27") appendDevCmd(cmdobj.SN, "REBOOT") else: appendDevCmd(cmdobj.SN, cmdobj.CmdContent) #重新升级
def cdata(request): encrypt = 1 response = HttpResponse(mimetype='text/plain') getResp = "" try: cursor = conn.cursor() resp = "" device = checkDevice(request, response) if(device == None): return response if request.REQUEST.has_key('action'): resp += "OK\n" elif request.method == 'GET': if request.REQUEST.has_key('PIN'): save = request.REQUEST.has_key('save') and (request.REQUEST['save'] in ['1', 'Y', 'y', 'yes', 'YES']) or False try: pin = request.REQUEST['PIN'] emp = employee.objects.get(PIN=formatPIN(pin)) except ObjectDoesNotExist: resp += "NONE" else: cc = u"DATA UPDATE USERINFO PIN=%s\tName=%s\tPasswd=%s\tGrp=%d\tCard=%s\tTZ=%s\tPri=%s\n" % (emp.pin(), emp.EName or "", emp.Password or "", emp.AccGroup or 1, getNormalCard(emp.Card), emp.TimeZones or "", save and emp.Privilege or 0) for fp in fptemp.objects.filter(UserID=emp): try: #cc+=u"DATA FP PIN=%s\tFID=%d\tTMP=%s\n"%(emp.pin(), fp.FingerID, fp.temp()) cc += u"DATA UPDATE FINGERTMP PIN=%s\tFID=%d\tSize=%s\tTMP=%s\n" % (emp.pin(), fp.FingerID, len(fp.temp()), fp.temp()) #by super 2010-07-24 except:pass try: resp += cc.encode("gb18030") except: resp += cc.decode("utf-8").encode("gb18030") if not save: # if not saved user in device, delete it after serveral(5) minutes endTime = datetime.datetime.now() + datetime.timedelta(0, 5 * 60) appendDevCmd(device, "DATA DELETE USERINFO PIN=%s" % emp.pin(), cursor, endTime) else: #by super 2010-08-25 协议向下兼容 pushverValue = None if request.REQUEST.has_key('pushver'): pushverValue = request.REQUEST['pushver'] attlogStamp = "Stamp" operlogStamp = "OpStamp" attphotoStamp = "PhotoStamp" TransFlag = "0000000000" if pushverValue :#新协议 attlogStamp = "ATTLOGStamp" operlogStamp = "OPERLOGStamp" attphotoStamp = "ATTPHOTOStamp" #TransFlag = device.UpdateDB.replace("\\t", "\t") TransFlag = "1111000000" resp += "GET OPTION FROM: %s\n" % device.SN #resp+="Stamp=%s\n"%device.LogStamp #resp+="OpStamp=%s\n"%(device.OpLogStamp or 0) #resp+="PhotoStamp=%s\n"%(device.PhotoStamp or 0) # resp+="ATTLOGStamp=%s\n"%device.LogStamp # resp+="OPERLOGStamp=%s\n"%(device.OpLogStamp or 0) # resp+="ATTPHOTOStamp=%s\n"%(device.PhotoStamp or 0) resp += "%s=%s\n" % (attlogStamp, device.LogStamp) resp += "%s=%s\n" % (operlogStamp, device.OpLogStamp or 0) resp += "%s=%s\n" % (attphotoStamp, device.PhotoStamp or 0) resp += "ErrorDelay=%d\n" % max(30, settings.MIN_REQ_DELAY) resp += "Delay=%d\n" % settings.MIN_REQ_DELAY resp += "TransTimes=%s\n" % device.TransTimes resp += "TransInterval=%d\n" % max(settings.MIN_TRANSINTERVAL, device.TransInterval) resp += "TransFlag=%s\n" % device.UpdateDB.replace("\\t", "\t") #resp += "TransFlag=%s\n" % TransFlag#device.UpdateDB.replace("\\t","\t") #by super 2010-07-30 try: if not (device.TZAdj == None): resp += "TimeZone=%s\n" % device.TZAdj except: pass resp += "Realtime=%s\n" % settings.TRANS_REALTIME resp += "Encrypt=%s\n" % settings.ENCRYPT if pushverValue : resp += "ServerVer=0.0.2 2010-07-22\n" #2010-09-17 新版本才有服务版本信息和表明时间戳 resp += "TableNameStamp\n\n" encrypt = 0 checkAndSave(device) elif request.method == 'POST': raw_Data = request.raw_post_data if settings.ENCRYPT: import lzo rawData = lzo.bufferDecrypt(raw_Data, device.SN) else: rawData = raw_Data #by super 2010-08-16 将下发的用户信息保存到记事本 now = datetime.datetime.now() filepath = os.path.abspath(os.path.dirname(sys.argv[0])) old_file = "%s\\read\\%s_%s" % (tmpDir(), device.SN, now.strftime("%y%m%dT%H%M%S")) #考勤 if request.REQUEST.has_key('Stamp'): #and request.REQUEST.has_key('table'): if request.REQUEST.has_key('table'): #新协议 if request.REQUEST['table'] == 'ATTLOG':#by super 2010-07-22 上传考勤记录 s_data = ":TRANSACTIONS: SN=%s\tIP=%s\tTIME=%s\n%s\n\n" % (device.SN, real_ip(request), datetime.datetime.now(), rawData) #写入到队列,后台进程在进行实际的数据库写入操作 try: write_to_file(old_file, s_data.encode("utf-8")) #q_server=queqe_server() #q_server.lpush("TRANS", s_data) #q_server.connection.disconnect() except Exception, e: appendFile(e) resp += u"ERROR:%s\n" % e print u"ERROR:%s\n" % e raise e else: device.LogStamp = request.REQUEST['Stamp'] resp += "OK:%d\n" % 1 elif request.REQUEST['table'] == 'OPERLOG':#by super 2010-07-22 上传用户信息和系统日志 try: try: rawData.decode("ascii") except: rawData=rawData.decode("gb18030") s_data = u":OPLOG: SN=%s\tIP=%s\tTIME=%s\n%s\n\n" % (device.SN, real_ip(request), datetime.datetime.now(), rawData) except Exception, e: appendFile("--%s--%s" % (now, e)) raise e #s_data = u":OPLOG: SN=%s\tIP=%s\tTIME=%s\n%s\n\n" % (device.SN, #real_ip(request), #datetime.datetime.now(), #rawData) #写入到队列,后台进程在进行实际的数据库写入操作 try: write_to_file(old_file, s_data.encode("utf-8")) print 'success to write file' #q_server=queqe_server() #q_server.lpush("TRANsS", s_data.encode("utf-8")) #q_server.connection.disconnect() except Exception, e: resp += u"ERROR:%s\n" % e appendFile(e) errorLog(request) raise e else: device.OpLogStamp = request.REQUEST['Stamp'] resp += "OK:%d\n" % 1 elif request.REQUEST['table'] == 'ATTPHOTO':#by super 2010-07-24 上传照片 return postPhoto(request) else:
fldNames.append('TimeZones') values.append(tz) employee.TimeZones = tz except: appendFile("ERROR(lineToUser - USER):%s\nITEMS:%s" % (e,"error")) cmdStr = "DATA UPDATE USERINFO Name=%s\tPri=%s\tPasswd=%s\tCard=%s\tGrp=%s\tTZ=%s" % (flds["PIN"], ename or "", passwd or "", card and ((card != "[0000000000]") and card or "") or "", agrp, tz and (tz != "00000000" and tz or "") or "") try: employee.IsNewEmp except Exception, e: appendFile("ERROR(lineToUser - USER - insert database):%s\nSQL:%s" % (e, cmdStr)) employee.IsNewEmp = False if employee.IsNewEmp: if backDev: appendDevCmd(backDev, cmdStr, cursor) employee.IsNewEmp = False try: employee.save() except Exception, e: appendFile("ERROR(lineToUser - USER - save database)%s:%s\n" % (datetime.time, e)) sql = '' elif len(fldNames) > 2: #有新的用户信息 sql = u"update userinfo set %s where badgenumber='%s'" % (','.join([u"%s='%s'" % (fldNames[i], values[i]) for i in range(len(fldNames))]), pin) if backDev: appendDevCmd(backDev, cmdStr, cursor) else: sql = '' if sql: cursor.execute(sql) return employee
def dispatchEmpToAll(emp): for dev in iclock.objects.all(): if dev.State != DEV_STATUS_PAUSE and not dev.DelTag: s = getEmpCmdStr(emp) appendDevCmd(dev, s)
def deleteEmpFromAll(pin): for dev in iclock.objects.all(): appendDevCmd(dev, 'DATA DELETE USERINFO PIN=%s' % pin)
def deleteEmpFromAll(pin): for dev in iclock.objects.all(): appendDevCmd(dev, "DATA DELETE USERINFO PIN=%s"%pin)
def cdata(request): encrypt = 1 response = HttpResponse(mimetype='text/plain') getResp = '' try: cursor = conn.cursor() resp = '' device = checkDevice(request, response) if device == None: return response if request.REQUEST.has_key('action'): resp += 'OK\n' if request.method == 'GET': if request.REQUEST.has_key('PIN'): save = request.REQUEST.has_key('save') and request.REQUEST['save'] in ('1', 'Y', 'y', 'yes', 'YES') or False try: pin = request.REQUEST['PIN'] emp = employee.objects.get(PIN=formatPIN(pin)) except ObjectDoesNotExist: resp += 'NONE' else: cc = u'DATA UPDATE USERINFO PIN=%s\tName=%s\tPasswd=%s\tGrp=%d\tCard=%s\tTZ=%s\tPri=%s\n' % ( emp.pin(), emp.EName or '', emp.Password or '', emp.AccGroup or 1, getNormalCard(emp.Card), emp.TimeZones or '', save and emp.Privilege or 0) for fp in fptemp.objects.filter(UserID=emp): try: cc += u'DATA UPDATE FINGERTMP PIN=%s\tFID=%d\tSize=%s\tTMP=%s\n' % ( emp.pin(), fp.FingerID, len(fp.temp()), fp.temp()) except: pass try: resp += cc.encode('gb18030') except: resp += cc.decode('utf-8').encode('gb18030') else: endTime = save or datetime.datetime.now() + datetime.timedelta(0, 300) appendDevCmd(device, 'DATA DELETE USERINFO PIN=%s' % emp.pin(), cursor, endTime) pushverValue = None if request.REQUEST.has_key('pushver'): pushverValue = request.REQUEST['pushver'] attlogStamp = 'Stamp' operlogStamp = 'OpStamp' attphotoStamp = 'PhotoStamp' TransFlag = '0000000000' if pushverValue: attlogStamp = 'ATTLOGStamp' operlogStamp = 'OPERLOGStamp' attphotoStamp = 'ATTPHOTOStamp' TransFlag = '1111000000' resp += 'GET OPTION FROM: %s\n' % device.SN resp += '%s=%s\n' % (attlogStamp, device.LogStamp) resp += '%s=%s\n' % (operlogStamp, device.OpLogStamp or 0) resp += '%s=%s\n' % (attphotoStamp, device.PhotoStamp or 0) resp += 'ErrorDelay=%d\n' % max(30, settings.MIN_REQ_DELAY) resp += 'Delay=%d\n' % settings.MIN_REQ_DELAY resp += 'TransTimes=%s\n' % device.TransTimes resp += 'TransInterval=%d\n' % max(settings.MIN_TRANSINTERVAL, device.TransInterval) resp += 'TransFlag=%s\n' % device.UpdateDB.replace('\\t', '\t') try: if not device.TZAdj == None: if device.TZAdj == 14: resp += 'TimeZone=0\n' else: resp += 'TimeZone=%s\n' % device.TZAdj except: pass else: resp += 'Realtime=%s\n' % settings.TRANS_REALTIME resp += 'Encrypt=%s\n' % settings.ENCRYPT if pushverValue: resp += 'ServerVer=0.0.2 2010-07-22\n' resp += 'TableNameStamp\n\n' encrypt = 0 checkAndSave(device) else: if request.method == 'POST': raw_Data = request.raw_post_data if settings.ENCRYPT: import lzo rawData = lzo.bufferDecrypt(raw_Data, device.SN) else: rawData = raw_Data now = datetime.datetime.now() filepath = os.path.abspath(os.path.dirname(sys.argv[0])) old_file = '%s\\read\\%s_%s' % (tmpDir(), device.SN, now.strftime('%y%m%dT%H%M%S')) if request.REQUEST.has_key('Stamp') and request.REQUEST.has_key('table'): if request.REQUEST['table'] == 'ATTLOG': s_data = ':TRANSACTIONS: SN=%s\tIP=%s\tTIME=%s\n%s\n\n' % (device.SN, real_ip(request), datetime.datetime.now(), rawData) try: write_to_file(old_file, s_data.encode('utf-8')) except Exception, e: appendFile(e) resp += u'ERROR:%s\n' % e print u'ERROR:%s\n' % e raise e else: device.LogStamp = request.REQUEST['Stamp'] resp += 'OK:1\n' elif request.REQUEST['table'] == 'OPERLOG': try: s_data = u':OPLOG: SN=%s\tIP=%s\tTIME=%s\n%s\n\n' % (device.SN, real_ip(request), datetime.datetime.now(), decode_data(rawData)) except Exception, e: appendFile('--%s--%s' % (now, e)) raise e else: try: write_to_file(old_file, s_data.encode('utf-8')) print 'success to write file' except Exception, e: resp += u'ERROR:%s\n' % e appendFile(e) errorLog(request) raise e else: device.OpLogStamp = request.REQUEST['Stamp'] resp += 'OK:1\n' elif request.REQUEST['table'] == 'ATTPHOTO': return postPhoto(request)
employee.TimeZones = tz except: appendFile('ERROR(lineToUser - USER):%s\nITEMS:%s' % (e, 'error')) else: cmdStr = 'DATA UPDATE USERINFO Name=%s\tPri=%s\tPasswd=%s\tCard=%s\tGrp=%s\tTZ=%s' % ( flds['PIN'], ename or '', passwd or '', card and (card != '[0000000000]' and card or '') or '', agrp, tz and (tz != '00000000' and tz or '') or '') try: employee.IsNewEmp except Exception, e: appendFile('ERROR(lineToUser - USER - insert database):%s\nSQL:%s' % (e, cmdStr)) employee.IsNewEmp = False else: if employee.IsNewEmp and backDev: appendDevCmd(backDev, cmdStr, cursor) employee.IsNewEmp = False try: employee.save() except Exception, e: appendFile('ERROR(lineToUser - USER - save database)%s:%s\n' % (datetime.time, e)) else: sql = '' else: if len(fldNames) > 2: sql = u"update userinfo set %s where badgenumber='%s'" % ( (',').join([u"%s='%s'" % (fldNames[i], values[i]) for i in range(len(fldNames))]), pin) if backDev: appendDevCmd(backDev, cmdStr, cursor) else: sql = ''
def dispatchEmpToAll(emp): for dev in iclock.objects.all(): if (dev.State<>DEV_STATUS_PAUSE) and not dev.DelTag: s=getEmpCmdStr(emp) appendDevCmd(dev, s)