Exemplo n.º 1
0
 def Run(self):
     with self.protocol.lockCmd:
         if not self.Authorized(): 
             self.SendUnauthorizedResp()
             return
         CBaseCommand.Run(self)
         apartment_id=self.body[BaseCommand.PN_APARTMENTID]
         name=self.body[BaseCommand.PN_CONTACTORNAME]
         mobile_phone=self.body.get(BaseCommand.PN_MOBLEPHONE,None)
         respond=self.GetResp()
         with SBDB.session_scope() as session :
             try:
                 apartment=SBDB.IncreaseVersion(session, apartment_id)
                 contactor=SBDB_ORM.Contactor()
                 contactor.apartment_id=apartment_id
                 contactor.mobile_phone=mobile_phone
                 contactor.name=name  
                 session.add(contactor)
                 respond.body[BaseCommand.PN_VERSION]=apartment.version
                 session.commit()
                 respond.body[BaseCommand.PN_ID]=contactor.id
             except SQLAlchemyError,e:
                 respond.SetErrorCode(BaseCommand.CS_DBEXCEPTION)
                 logging.error("transport %d:%s",id(self.protocol.transport),e)
                 session.rollback()
         respond.Send()
 def Run(self):
     with self.protocol.lockCmd:
         CBaseCommand.Run(self)
         with SBDB.session_scope() as session :
             respond=self.GetResp()
             email=self.body.get(BaseCommand.PN_EMAIL,None)
             account_id,=session.query(SBDB_ORM.Account.id).filter(SBDB_ORM.Account.email==email).first()
             if email is None:
                 respond.SetErrorCode(BaseCommand.CS_NOTFOUNDEMAIL)
             elif account_id is None:
                 respond.SetErrorCode(BaseCommand.CS_NOTFOUNDEMAIL)
 #             elif 'dt_restore_require' in dir(self.protocol) and (datetime.datetime.now()-self.protocol.dt_restore_require).seconds<Config.second_restore_require:
 #                 respond.SetErrorCode(BaseCommand.CS_TRYLATER)
             else: 
                 try:
                     content=open(os.path.join(Config.dir_local_static,"restore_confirm.html"),'r').read()
                     url=Util.GenRestoreURL(account_id)
                     content=content.replace("{{url_restore}}",url)
                     #emaillib.SendEmail("Honeywell Smart Home: reset password confirm", content, [self.protocol.account.email])
                     threading.Thread(target=emaillib.SendEmail,args=("Honeywell Smart Home: reset password confirm", content, [email])).start()
                     self.protocol.dt_restore_require=datetime.datetime.now()
                 except SQLAlchemyError,e:
                     respond.SetErrorCode(BaseCommand.CS_DBEXCEPTION)
                     logging.error("transport %d:%s",id(self.protocol.transport),e)
                     session.rollback()
         respond.Send()
 def Run(self):
     with self.protocol.lockCmd:
         if not self.Authorized(): 
             self.SendUnauthorizedResp()
             return
         CBaseCommand.Run(self)
         with SBDB.session_scope() as session :
             contactor_id=self.body[BaseCommand.PN_ID]
             apartment_id,=session.query(SBDB_ORM.Apartment.id).join(SBDB_ORM.Contactor).filter(SBDB_ORM.Contactor.id==contactor_id).one()
             name=self.body.get(BaseCommand.PN_CONTACTORNAME,None)
             mobile_phone=self.body.get(BaseCommand.PN_MOBLEPHONE,None)
             respond=self.GetResp()
             if contactor_id is None :
                 respond.SetErrorCode(BaseCommand.CS_PARAMLACK)
             else:
                 try:
                     apartment=SBDB.IncreaseVersion(session, apartment_id)
                     contactor=session.query(SBDB_ORM.Contactor).filter(SBDB_ORM.Contactor.id==contactor_id).first()
                     if name is not None:    contactor.name=name
                     if mobile_phone is not None: contactor.mobile_phone=mobile_phone
                     respond.body[BaseCommand.PN_VERSION]=apartment.version
                     session.commit()
                 except SQLAlchemyError,e:
                     respond.SetErrorCode(BaseCommand.CS_DBEXCEPTION)
                     logging.error("transport %d:%s",id(self.protocol.transport),e)
                     session.rollback()
         respond.Send()
Exemplo n.º 4
0
 def Run(self):
     with self.protocol.lockCmd:
         if not self.Authorized(): 
             self.SendUnauthorizedResp()
             return
         CBaseCommand.Run(self)
         apartment_id=self.body[BaseCommand.PN_APARTMENTID]
         name=self.body[BaseCommand.PN_APARTMENTNAME]
         scene_contents=self.body.get(BaseCommand.PN_SCENECONTENTS)
         respond=self.GetResp()
         with SBDB.session_scope() as session :
             try:
                 apartment=SBDB.IncreaseVersion(session, apartment_id)
                 scene=SBDB_ORM.Scene()
                 scene.apartment_id=apartment_id
                 scene.name=name
                 if scene_contents is not None:
                     for scene_content in scene_contents:
                         sc=SBDB_ORM.SceneContent()
                         sc.value=scene_content[BaseCommand.PN_DEVVALUE]
                         sc.device_key_code_id,=session.query(SBDB_ORM.DeviceKeyCode.id).join(SBDB_ORM.DeviceKey).filter(and_(SBDB_ORM.DeviceKeyCode.device_id==scene_content[BaseCommand.PN_DEVICEID],SBDB_ORM.DeviceKey.seq==scene_content[BaseCommand.PN_DEVSEQ])).one()
                         scene.scene_contents.append(sc)
                 session.add(scene)
                 respond.body[BaseCommand.PN_VERSION]=apartment.version
                 session.commit()
                 respond.body[BaseCommand.PN_ID]=scene.id
             except SQLAlchemyError,e:
                 respond.SetErrorCode(BaseCommand.CS_DBEXCEPTION)
                 logging.error("transport %d:%s",id(self.protocol.transport),e)
                 session.rollback()
         respond.Send()
         
Exemplo n.º 5
0
 def Run(self):
     with self.protocol.lockCmd:
         if not self.Authorized():
             self.SendUnauthorizedResp()
             return
         CBaseCommand.Run(self)
         name = self.body[BaseCommand.PN_APARTMENTNAME]
         respond = self.GetResp()
         with SBDB.session_scope() as session:
             try:
                 # SBDB.IncreaseVersion(session, self.protocol.account)
                 apartment = SBDB_ORM.Apartment()
                 apartment.account_id = self.protocol.account_id
                 apartment.arm_state = BaseCommand.PV_ARM_OFF
                 apartment.name = name
                 apartment.scene_id = None
                 apartment.version = 0
                 session.add(apartment)
                 respond.body[BaseCommand.PN_VERSION] = apartment.version
                 session.commit()
                 respond.body[BaseCommand.PN_ID] = apartment.id
             except SQLAlchemyError, e:
                 respond.SetErrorCode(BaseCommand.CS_DBEXCEPTION)
                 logging.error("transport %d:%s", id(self.protocol.transport), e)
                 session.rollback()
         respond.Send()
Exemplo n.º 6
0
 def Run(self):
     with self.protocol.lockCmd:
         if not self.Authorized(): 
             self.SendUnauthorizedResp()
             return
         CBaseCommand.Run(self)
         with SBDB.session_scope() as session :
             account_id=self.protocol.account_id
             respond=self.GetResp()
             try:
                 account=session.query(SBDB_ORM.Account).filter(SBDB_ORM.Account.id==account_id).one()
                 respond.body[BaseCommand.PN_LANGUAGENAME]=account.language.language
                 respond.body[BaseCommand.PN_USERNAME]=account.user_name
                 respond.body[BaseCommand.PN_MOBLEPHONE]=account.mobile_phone
                 respond.body[BaseCommand.PN_EMAIL]=account.email
                 '''
                 # move this parameter to Authorize Command
                 listApartment=[]
                 for apartment in account.apartments:
                     elementApartment={}
                     elementApartment[BaseCommand.PN_ID]=apartment.id
                     listApartment.append(elementApartment)
                 respond.body[BaseCommand.PN_APARTMENTS]=listApartment
                 '''
                     
             except SQLAlchemyError,e:
                 respond.SetErrorCode(BaseCommand.CS_DBEXCEPTION)
                 logging.error("transport %d:%s",id(self.protocol.transport),e)
                 session.rollback()
         respond.Send()
 def Run(self):
     with self.protocol.lockCmd:
         if not self.Authorized():
             self.SendUnauthorizedResp()
             return
         CBaseCommand.Run(self)
         with SBDB.session_scope() as session:
             password = self.body.get(BaseCommand.PN_PASSWORD)
             email = self.body.get(BaseCommand.PN_EMAIL)
             language_name = self.body.get(BaseCommand.PN_LANGUAGENAME)
             mobile_phone = self.body.get(BaseCommand.PN_MOBLEPHONE)
             respond = self.GetResp()
             try:
                 account = (
                     session.query(SBDB_ORM.Account).filter(SBDB_ORM.Account.id == self.protocol.account_id).one()
                 )
                 if password is not None:
                     account.password = Util.hash_password(password)
                 if email is not None:
                     account.email = email
                 if language_name is not None:
                     for language in session.query(SBDB_ORM.Language).all():
                         if language.language == language_name:
                             account.language_id = language.id
                 if mobile_phone is not None:
                     account.mobile_phone = mobile_phone
                 session.commit()
             except SQLAlchemyError, e:
                 respond.SetErrorCode(BaseCommand.CS_DBEXCEPTION)
                 logging.error("transport %d:%s", id(self.protocol.transport), e)
                 session.rollback()
         respond.Send()
 def Run(self):
     with self.protocol.lockCmd:
         if not self.Authorized(): 
             self.SendUnauthorizedResp()
             return
         CBaseCommand.Run(self)
         with SBDB.session_scope() as session :
             apartment_id=self.body[BaseCommand.PN_APARTMENTID]
             sb_id=self.body[BaseCommand.PN_SUPERBOXID]
             sb_code=self.body.get(BaseCommand.PN_SB_CODE,None)
             name=self.body.get(BaseCommand.PN_NAME,None)
             respond=self.GetResp()
             if sb_id is None:
                 respond.SetErrorCode(BaseCommand.CS_PARAMLACK)
             else:
                 try:
                     apartment=None
                     if sb_code is None:
                         apartment=SBDB.IncreaseVersion(session, apartment_id)
                     else:
                         apartment=SBDB.IncreaseVersions(session, 0,apartment_id)
                     superbox,apartment_superbox=session.query(SBDB_ORM.Superbox,SBDB_ORM.Apartment_Superbox).join(SBDB_ORM.Apartment_Superbox).filter(and_(SBDB_ORM.Superbox.id==sb_id,SBDB_ORM.Apartment_Superbox.apartment_id==apartment_id)).first()
                     if name is not None:    apartment_superbox.name=name
                     if sb_code is not None: superbox.uni_code=sb_code
                     respond.body[BaseCommand.PN_VERSION]=apartment.version
                     session.commit()
                 except SQLAlchemyError,e:
                     respond.SetErrorCode(BaseCommand.CS_DBEXCEPTION)
                     logging.error("transport %d:%s",id(self.protocol.transport),e)
                     session.rollback()
         respond.Send()
Exemplo n.º 9
0
def GetDefaultTemplate():
    with SBDB.session_scope() as session :
        defaultTemplate=session.query(SBDB_ORM.MessageTemplate).filter(and_(SBDB_ORM.MessageTemplate.language_id == None,SBDB_ORM.MessageTemplate.account_id == None,SBDB_ORM.MessageTemplate.sensor_model_id == None)).first()
        if defaultTemplate is None:
            defaultTemplate=SBDB_ORM.MessageTemplate()
            defaultTemplate.template="[apartment]的[device]于[time]发生[type]告警"
            session.add(defaultTemplate)
            session.commit()
    return defaultTemplate
Exemplo n.º 10
0
 def FeedbackIfFinished(self):
     if not self.CheckFinished():    return
     respond=self.Feedback()
     if respond is None: return
     special_scene=self.body.get(BaseCommand.PN_SPECIALSCENE,BaseCommand.PV_SCENE_SPECIFIED)
     if respond.command_status==BaseCommand.CS_OK and special_scene ==BaseCommand.PV_SCENE_SPECIFIED:
         scene_id=self.body[BaseCommand.PN_ID]
         with SBDB.session_scope() as session :
             scene=session.query(SBDB_ORM.Scene).filter(SBDB_ORM.Scene.id==scene_id).one()
             scene.apartment.scene_id=scene_id
             session.commit()
Exemplo n.º 11
0
def GenRestoreURL(account_id):
    from DB import SBDB, SBDB_ORM
    uuid_restore=GenUUID()
    with SBDB.session_scope() as session :
        restore=SBDB_ORM.RestoreRequire()
        restore.account_id=account_id
        restore.dt=datetime.datetime.now()
        restore.finished=False
        restore.uuid=uuid_restore
        session.add(restore)
        session.commit()
    return "https://www.honhome.com/customer/reset_password/"+uuid_restore
Exemplo n.º 12
0
def GenRestoreURL(account_id):
    from DB import SBDB, SBDB_ORM
    uuid_restore = GenUUID()
    with SBDB.session_scope() as session:
        restore = SBDB_ORM.RestoreRequire()
        restore.account_id = account_id
        restore.dt = datetime.datetime.now()
        restore.finished = False
        restore.uuid = uuid_restore
        session.add(restore)
        session.commit()
    return "https://www.honhome.com/customer/reset_password/" + uuid_restore
Exemplo n.º 13
0
def GetDefaultTemplate():
    with SBDB.session_scope() as session:
        defaultTemplate = session.query(SBDB_ORM.MessageTemplate).filter(
            and_(SBDB_ORM.MessageTemplate.language_id == None,
                 SBDB_ORM.MessageTemplate.account_id == None,
                 SBDB_ORM.MessageTemplate.sensor_model_id == None)).first()
        if defaultTemplate is None:
            defaultTemplate = SBDB_ORM.MessageTemplate()
            defaultTemplate.template = "[apartment]的[device]于[time]发生[type]告警"
            session.add(defaultTemplate)
            session.commit()
    return defaultTemplate
Exemplo n.º 14
0
 def FinishOne(self,superbox_id,control_device,respond):
     with self.lock:
         #deviceCmds=self.dictSendingSuperboxControls.get(superbox)
         deviceCmds=None
         for key in self.dictSendingSuperboxControls.keys():
             if key==superbox_id:
                 deviceCmds=self.dictSendingSuperboxControls[key]
         if deviceCmds is not None:
             for deviceCmd in deviceCmds:
                 if control_device.body[BaseCommand.PN_DEVMODEL]==deviceCmd.dev_model and control_device.body[BaseCommand.PN_DEVCODE]==deviceCmd.dev_code and control_device.body[BaseCommand.PN_DEVSEQ]==deviceCmd.dev_seq:
                     if deviceCmd.result!=0: 
                         deviceCmd.result=respond.command_status
                         deviceCmd.body=respond.body
                         
                         #if it's failed, and have not try other superbox in the same account: add these superbox to dictWaitingSuperboxControls
                         if deviceCmd.result!=0 and not deviceCmd.bTriedSuperboxMain and self.protocol.role==BaseCommand.PV_ROLE_HUMAN:
                             with SBDB.session_scope() as session :
                                 deviceCmd.bTriedSuperboxMain=True
                                 
                                 listSuperboxId=[]
                                 for s in session.query(SBDB_ORM.Superbox).join(SBDB_ORM.Apartment_Superbox).join(SBDB_ORM.Apartment).join(SBDB_ORM.Account).join(SBDB_ORM.ApartmentDevice).join(SBDB_ORM.Device).join(SBDB_ORM.DeviceModel).filter(and_(SBDB_ORM.Account.id==self.protocol.account_id,SBDB_ORM.Device.uni_code==deviceCmd.dev_code,SBDB_ORM.DeviceModel.name==deviceCmd.dev_model,SBDB_ORM.Superbox.id!=superbox_id)):
                                     if s.id not in listSuperboxId:
                                         listSuperboxId.append(s.id)
                                 if len(listSuperboxId)>0:
                                     deviceCmd.result=-1
                                     deviceCmds.remove(deviceCmd)
                                     for s in listSuperboxId:
                                         if self.dictWaitingSuperboxControls.has_key(s):
                                             self.dictWaitingSuperboxControls[s].append(deviceCmd)
                                         else:
                                             self.dictWaitingSuperboxControls[s]=[deviceCmd,]
                                     
                     #if it's succeed finished by other superbox, set this superbox as this device's mainSueprbox
                     if deviceCmd.result==0 and deviceCmd.bTriedSuperboxMain:
                         with SBDB.session_scope() as session :
                             for apartment_device in session.query(SBDB_ORM.ApartmentDevice).join(SBDB_ORM.Device).join(SBDB_ORM.Apartment).join(SBDB_ORM.Account).filter(and_(SBDB_ORM.Account.id==self.protocol.account_id,SBDB_ORM.Device.uni_code==deviceCmd.dev_code)):
                                 apartment_device.superbox_id=superbox_id
                             session.commit()                            
                     break
         self.FeedbackIfFinished()
Exemplo n.º 15
0
 def Run(self):
     with self.protocol.lockCmd:
         if not self.Authorized(): 
             self.SendUnauthorizedResp()
             return
         CBaseCommand.Run(self)
         apartment_id=self.body[BaseCommand.PN_APARTMENTID]
         sb_code=self.body[BaseCommand.PN_SB_CODE]
         sb_name=self.body[BaseCommand.PN_NAME]
         #account_id=self.protocol.account_id
         respond=self.GetResp()
         with SBDB.session_scope() as session :
             if session.query(SBDB_ORM.Relayer).join(SBDB_ORM.Apartment_Relayer).filter(and_(SBDB_ORM.Relayer.uni_code==sb_code,SBDB_ORM.Apartment_Relayer.apartment_id==apartment_id)).first() is not None:
                     respond.SetErrorCode(BaseCommand.CS_DEVICEEXIST)
             try:
                 relayer_id=SBDB.GetRelayerIdForcely(sb_code)
                 apartment=SBDB.IncreaseVersion(session, apartment_id)
                 apartment_relayer=SBDB_ORM.Apartment_Relayer()
                 apartment_relayer.apartment_id=apartment_id
                 apartment_relayer.relayer_id=relayer_id
                 apartment_relayer.name=sb_name
                 '''
                 relayer=SBDB_ORM.Relayer()
                 relayer.apartment_id=apartment_id
                 relayer.name=sb_name
                 relayer.uni_code=sb_code            
                 session.add(relayer)
                 '''
                 session.add(apartment_relayer)
                 respond.body[BaseCommand.PN_VERSION]=apartment.version
                 session.commit()
 #                 if session.query(SBDB_ORM.Device).join(SBDB_ORM.Relayer).filter(SBDB_ORM.Relayer.id==relayer.id).first():
 #                     respond.body[BaseCommand.PN_UPDATEDATA]=True
                 respond.body[BaseCommand.PN_ID]=relayer_id
             except SQLAlchemyError as e:
                 respond.SetErrorCode(BaseCommand.CS_DBEXCEPTION)
                 logging.error("transport %d:%s",id(self.protocol.transport),e)
                 session.rollback()
         respond.Send()
Exemplo n.º 16
0
 def Run(self):
     with self.protocol.lockCmd:
         if not self.Authorized(): 
             self.SendUnauthorizedResp()
             return
         CBaseCommand.Run(self)
         with SBDB.session_scope() as session :
             start_dt=self.body.get(BaseCommand.PN_STARTDT,"1999-01-01 00:00:00")
             end_dt=self.body.get(BaseCommand.PN_ENDDT,"2059-01-01 00:00:00")
             alarm_types=self.body.get(BaseCommand.PN_ALARMTYPES,None)
             device_ids=self.body.get(BaseCommand.PN_DEVICEIDS,None)
             apartment_ids=self.body.get(BaseCommand.PN_APARTMENTIDS,None)
             page=self.body[BaseCommand.PN_PAGE]
             
             respond=self.GetResp()
             try:
                 theQuery=session.query(SBDB_ORM.Alarm,SBDB_ORM.ApartmentDeviceKey.name).join(SBDB_ORM.Event).\
                 join(SBDB_ORM.DeviceKeyCode,SBDB_ORM.DeviceKeyCode.id==SBDB_ORM.Event.device_key_code_id).\
                 outerjoin(SBDB_ORM.ApartmentDeviceKey,and_(SBDB_ORM.ApartmentDeviceKey.device_key_code_id==SBDB_ORM.DeviceKeyCode.id,SBDB_ORM.ApartmentDeviceKey.apartment_device_id==SBDB_ORM.Alarm.apartment_device_id)).\
                 join(SBDB_ORM.ApartmentDevice,SBDB_ORM.ApartmentDeviceKey.apartment_device_id==SBDB_ORM.ApartmentDevice.id).\
                 join(SBDB_ORM.Apartment,SBDB_ORM.Apartment.id==SBDB_ORM.ApartmentDevice.apartment_id).filter(and_(SBDB_ORM.Event.dt.between(start_dt,end_dt),SBDB_ORM.Apartment.account_id==self.protocol.account_id))
                 if apartment_ids:
                     theQuery=theQuery.filter(SBDB_ORM.ApartmentDevice.apartment_id.in_(apartment_ids))
                 if device_ids:
                     theQuery=theQuery.filter(SBDB_ORM.DeviceKeyCode.device_id.in_(device_ids))
                 if alarm_types:
                     theQuery=theQuery.join(SBDB_ORM.Device).join(SBDB_ORM.DeviceModel).join(SBDB_ORM.DeviceType).filter(SBDB_ORM.DeviceType.name.in_(alarm_types))
                 
                 theQuery=theQuery.order_by(SBDB_ORM.Alarm.id.desc()).offset(CQueryAlarm.PAGELIMIT*page).limit(CQueryAlarm.PAGELIMIT)
                 listAlarms=[]
                 for row in theQuery:
                     alarm=row.Alarm
                     dev_key_name=row.name
                     if dev_key_name is None:    dev_key_name="N/A"
                     alarm_item={}
                     alarm_item[BaseCommand.PN_ID]=alarm.id
                     alarm_item[BaseCommand.PN_APARTMENTID]=alarm.apartment_device.apartment_id
                     alarm_item[BaseCommand.PN_DEVICETYPENAME]=alarm.event.device_key_code.device.device_model.device_type.name
                     alarm_item[BaseCommand.PN_DEVICEID]=alarm.event.device_key_code.device_id
                     alarm_item[BaseCommand.PN_DT]=alarm.event.dt.strftime("%Y-%m-%d %H:%M:%S")  
                     alarm_item[BaseCommand.PN_DEVCODE]=alarm.event.device_key_code.device.uni_code
                     alarm_item[BaseCommand.PN_DEVNAME]=dev_key_name
                     alarm_item[BaseCommand.PN_DEVMODEL]=alarm.event.device_key_code.device.device_model.name
                     listAlarms.append(alarm_item)
                 respond.body[BaseCommand.PN_ALARMS]=listAlarms
                     
             except SQLAlchemyError,e:
                 respond.SetErrorCode(BaseCommand.CS_DBEXCEPTION)
                 logging.error("transport %d:%s",id(self.protocol.transport),e)
                 session.rollback()
         respond.Send()
Exemplo n.º 17
0
 def Run(self):
     with self.protocol.lockCmd:
         if not self.Authorized(): 
             self.SendUnauthorizedResp()
             return
         CBaseCommand.Run(self)
         with SBDB.session_scope() as session :
             start_dt=self.body.get(BaseCommand.PN_STARTDT,"1999-01-01 00:00:00")
             end_dt=self.body.get(BaseCommand.PN_ENDDT,"2059-01-01 00:00:00")
             alarm_types=self.body.get(BaseCommand.PN_ALARMTYPES,None)
             device_ids=self.body.get(BaseCommand.PN_DEVICEIDS,None)
             apartment_ids=self.body.get(BaseCommand.PN_APARTMENTIDS,None)
             page=self.body[BaseCommand.PN_PAGE]
             
             respond=self.GetResp()
             try:
                 theQuery=session.query(SBDB_ORM.Alarm,SBDB_ORM.ApartmentDeviceKey.name).join(SBDB_ORM.Event).\
                 join(SBDB_ORM.DeviceKeyCode,SBDB_ORM.DeviceKeyCode.id==SBDB_ORM.Event.device_key_code_id).\
                 outerjoin(SBDB_ORM.ApartmentDeviceKey,and_(SBDB_ORM.ApartmentDeviceKey.device_key_code_id==SBDB_ORM.DeviceKeyCode.id,SBDB_ORM.ApartmentDeviceKey.apartment_device_id==SBDB_ORM.Alarm.apartment_device_id)).\
                 join(SBDB_ORM.ApartmentDevice,SBDB_ORM.ApartmentDeviceKey.apartment_device_id==SBDB_ORM.ApartmentDevice.id).\
                 join(SBDB_ORM.Apartment,SBDB_ORM.Apartment.id==SBDB_ORM.ApartmentDevice.apartment_id).filter(and_(SBDB_ORM.Event.dt.between(start_dt,end_dt),SBDB_ORM.Apartment.account_id==self.protocol.account_id))
                 if apartment_ids:
                     theQuery=theQuery.filter(SBDB_ORM.ApartmentDevice.apartment_id.in_(apartment_ids))
                 if device_ids:
                     theQuery=theQuery.filter(SBDB_ORM.DeviceKeyCode.device_id.in_(device_ids))
                 if alarm_types:
                     theQuery=theQuery.join(SBDB_ORM.Device).join(SBDB_ORM.DeviceModel).join(SBDB_ORM.DeviceType).filter(SBDB_ORM.DeviceType.name.in_(alarm_types))
                 
                 theQuery=theQuery.order_by(SBDB_ORM.Alarm.id.desc()).offset(CQueryAlarm.PAGELIMIT*page).limit(CQueryAlarm.PAGELIMIT)
                 listAlarms=[]
                 for row in theQuery:
                     alarm=row.Alarm
                     dev_key_name=row.name
                     if dev_key_name is None:    dev_key_name="N/A"
                     alarm_item={}
                     alarm_item[BaseCommand.PN_ID]=alarm.id
                     alarm_item[BaseCommand.PN_APARTMENTID]=alarm.apartment_device.apartment_id
                     alarm_item[BaseCommand.PN_DEVICETYPENAME]=alarm.event.device_key_code.device.device_model.device_type.name
                     alarm_item[BaseCommand.PN_DEVICEID]=alarm.event.device_key_code.device_id
                     alarm_item[BaseCommand.PN_DT]=alarm.event.dt.strftime("%Y-%m-%d %H:%M:%S")  
                     alarm_item[BaseCommand.PN_DEVCODE]=alarm.event.device_key_code.device.uni_code
                     alarm_item[BaseCommand.PN_DEVNAME]=dev_key_name
                     alarm_item[BaseCommand.PN_DEVMODEL]=alarm.event.device_key_code.device.device_model.name
                     listAlarms.append(alarm_item)
                 respond.body[BaseCommand.PN_ALARMS]=listAlarms
                     
             except SQLAlchemyError,e:
                 respond.SetErrorCode(BaseCommand.CS_DBEXCEPTION)
                 logging.error("transport %d:%s",id(self.protocol.transport),e)
                 session.rollback()
         respond.Send()
Exemplo n.º 18
0
 def releaseFromDict(self):
     with self.factory.lockDict:
         if 'role' not in dir(self): return
         if self.role == Command.BaseCommand.PV_ROLE_RELAYER:
             if self.factory.dictRelayer.has_key(self.relayer_id):
                 if self.factory.dictRelayer[self.relayer_id]==self:
                     self.factory.dictRelayer.pop(self.relayer_id)
         elif self.role == Command.BaseCommand.PV_ROLE_HUMAN:
             for relayerId in SBDB.GetRelayerIDsByAccountId(self.account_id):
                 if self.factory.dictAccounts.has_key(relayerId):
                     listAccount=self.factory.dictAccounts[relayerId]
                     if self in listAccount:
                         listAccount.remove(self)
                         if len(listAccount)<=0:
                             self.factory.dictAccounts.pop(relayerId)
Exemplo n.º 19
0
 def Run(self):
     with self.protocol.lockCmd:
         if not self.Authorized(): 
             self.SendUnauthorizedResp()
             return
         CBaseCommand.Run(self)
         with SBDB.session_scope() as session :
             apartment_id=self.body[BaseCommand.PN_ID]
             apartment_name=self.body[BaseCommand.PN_NAME]
             respond=self.GetResp()
             if apartment_id is None or apartment_name is None:
                 respond.SetErrorCode(BaseCommand.CS_PARAMLACK)
             else:
                 try:
                     SBDB.IncreaseVersion(session, apartment_id)
                     apartment=session.query(SBDB_ORM.Apartment).filter(SBDB_ORM.Apartment.id==apartment_id).first()
                     apartment.name=apartment_name
                     respond.body[BaseCommand.PN_VERSION]=apartment.version
                     session.commit()
                 except SQLAlchemyError,e:
                     respond.SetErrorCode(BaseCommand.CS_DBEXCEPTION)
                     logging.error("transport %d:%s",id(self.protocol.transport),e)
                     session.rollback()
         respond.Send()
Exemplo n.º 20
0
    def __init__(self,data=None,protocol=None,client_id=0):
        '''
        Constructor
        '''
        CBaseNotify.__init__(self, data, protocol,client_id)        
        
        if protocol is not None:

#             self.superbox_id=protocol.superbox_id
#             print "superbox_id is ", self.superbox_id, "xxxxxxxxxxxxxxxxxxxxx"
            with SBDB.session_scope() as session :
                self.body[BaseCommand.PN_DEVCODE]=self.body[BaseCommand.PN_DEVCODE].upper()
                print "-----",self.body[BaseCommand.PN_DEVCODE],"----",client_id,"---",self.body[BaseCommand.PN_DEVSEQ]
                self.body[BaseCommand.PN_DEVNAME],=session.query(SBDB_ORM.ApartmentDeviceKey.name).join(SBDB_ORM.DeviceKeyCode).join(SBDB_ORM.DeviceKey).join(SBDB_ORM.Device,SBDB_ORM.Device.id==SBDB_ORM.DeviceKeyCode.device_id).join(SBDB_ORM.ApartmentDevice).join(SBDB_ORM.Apartment).join(SBDB_ORM.Account).join(SBDB_ORM.Client).filter(and_(SBDB_ORM.Client.id==client_id,SBDB_ORM.Device.uni_code==self.body[BaseCommand.PN_DEVCODE],SBDB_ORM.DeviceKey.seq==self.body[BaseCommand.PN_DEVSEQ])).first()
                self.body[BaseCommand.PN_DEVMODEL],=session.query(SBDB_ORM.DeviceModel.name).join(SBDB_ORM.Device).filter(SBDB_ORM.Device.uni_code==self.body[BaseCommand.PN_DEVCODE]).first()
                self.body[BaseCommand.PN_ISALARM]="True"
Exemplo n.º 21
0
 def Run(self): 
     with self.protocol.lockCmd:
         CBaseCommand.Run(self)
         user_name=self.body.get(BaseCommand.PN_USERNAME)
         if user_name is not None:   user_name=user_name.strip()
         password=self.body[BaseCommand.PN_PASSWORD]
         email=self.body.get(BaseCommand.PN_EMAIL)
         if email is not None:   email=email.strip()
         mobile_phone=self.body.get(BaseCommand.PN_MOBLEPHONE)
         if mobile_phone is not None:   mobile_phone=mobile_phone.strip()
         respond=self.GetResp()
         with SBDB.session_scope() as session :
             if user_name is None and password is None and email is None:
                 respond.SetErrorCode(BaseCommand.CS_PARAMLACK)
             elif user_name is not None and (session.query(SBDB_ORM.Account).filter(or_(SBDB_ORM.Account.user_name==user_name,SBDB_ORM.Account.email==user_name,SBDB_ORM.Account.mobile_phone==user_name)).first() is not None or len(user_name)<2):
                 respond.SetErrorCode(BaseCommand.CS_USERNAME)
             elif email is not None and (session.query(SBDB_ORM.Account).filter(or_(SBDB_ORM.Account.user_name==email,SBDB_ORM.Account.email==email,SBDB_ORM.Account.mobile_phone==email)).first() is not None or not Util.validateEmail(email)):
                 respond.SetErrorCode(BaseCommand.CS_EMAIL)
             elif mobile_phone is not None and (session.query(SBDB_ORM.Account).filter(or_(SBDB_ORM.Account.user_name==mobile_phone,SBDB_ORM.Account.email==mobile_phone,SBDB_ORM.Account.mobile_phone==mobile_phone)).first() is not None or not Util.validateMobilePhone(mobile_phone)):
                 respond.SetErrorCode(BaseCommand.CS_MOBILEPHONE)
             else:
                 try:
                     account=SBDB_ORM.Account()
                     account.language_id=2
                     account.email=email
                     #account.password=password
                     account.password=Util.hash_password(password)
                     account.user_name=user_name
                     account.mobile_phone=mobile_phone
                     account.version=0
                     apartment=SBDB_ORM.Apartment()
                     apartment.arm_state=BaseCommand.PV_ARM_OFF
                     apartment.name="Home"
                     apartment.scene_id=None  
                     apartment.version=0          
                     account.apartments.append(apartment)
                     session.add(account)
                     session.commit()
                     respond.body[BaseCommand.PN_VERSION]=apartment.version
                     respond.body[BaseCommand.PN_APARTMENTID]=apartment.id
                     respond.body[BaseCommand.PN_NAME]=apartment.name              
                 except SQLAlchemyError,e:
                     respond.SetErrorCode(BaseCommand.CS_DBEXCEPTION)
                     logging.error("transport %d:%s",id(self.protocol.transport),e)
                     session.rollback()
         respond.Send()
Exemplo n.º 22
0
 def Run(self): 
     with self.protocol.lockCmd:
         CBaseCommand.Run(self)
         user_name=self.body.get(BaseCommand.PN_USERNAME)
         if user_name is not None:   user_name=user_name.strip()
         password=self.body[BaseCommand.PN_PASSWORD]
         email=self.body.get(BaseCommand.PN_EMAIL)
         if email is not None:   email=email.strip()
         mobile_phone=self.body.get(BaseCommand.PN_MOBLEPHONE)
         if mobile_phone is not None:   mobile_phone=mobile_phone.strip()
         respond=self.GetResp()
         with SBDB.session_scope() as session :
             if user_name is None and password is None and email is None:
                 respond.SetErrorCode(BaseCommand.CS_PARAMLACK)
             elif user_name is not None and (session.query(SBDB_ORM.Account).filter(or_(SBDB_ORM.Account.user_name==user_name,SBDB_ORM.Account.email==user_name,SBDB_ORM.Account.mobile_phone==user_name)).first() is not None or len(user_name)<2):
                 respond.SetErrorCode(BaseCommand.CS_USERNAME)
             elif email is not None and (session.query(SBDB_ORM.Account).filter(or_(SBDB_ORM.Account.user_name==email,SBDB_ORM.Account.email==email,SBDB_ORM.Account.mobile_phone==email)).first() is not None or not Util.validateEmail(email)):
                 respond.SetErrorCode(BaseCommand.CS_EMAIL)
             elif mobile_phone is not None and (session.query(SBDB_ORM.Account).filter(or_(SBDB_ORM.Account.user_name==mobile_phone,SBDB_ORM.Account.email==mobile_phone,SBDB_ORM.Account.mobile_phone==mobile_phone)).first() is not None or not Util.validateMobilePhone(mobile_phone)):
                 respond.SetErrorCode(BaseCommand.CS_MOBILEPHONE)
             else:
                 try:
                     account=SBDB_ORM.Account()
                     account.language_id=2
                     account.email=email
                     #account.password=password
                     account.password=Util.hash_password(password)
                     account.user_name=user_name
                     account.mobile_phone=mobile_phone
                     account.version=0
                     apartment=SBDB_ORM.Apartment()
                     apartment.arm_state=BaseCommand.PV_ARM_OFF
                     apartment.name="Home"
                     apartment.scene_id=None  
                     apartment.version=0          
                     account.apartments.append(apartment)
                     session.add(account)
                     session.commit()
                     respond.body[BaseCommand.PN_VERSION]=apartment.version
                     respond.body[BaseCommand.PN_APARTMENTID]=apartment.id
                     respond.body[BaseCommand.PN_NAME]=apartment.name              
                 except SQLAlchemyError as e:
                     respond.SetErrorCode(BaseCommand.CS_DBEXCEPTION)
                     logging.error("transport %d:%s",id(self.protocol.transport),e)
                     session.rollback()
         respond.Send()
Exemplo n.º 23
0
    def initByDeviceCmdList(self, listDC):
        self.DeviceKeyCode = ""
        self.dictWaitingRelayerControls = {}
        setUnique = set()
        with SBDB.session_scope() as session:

            if self.internalMessage:
                self.account_id = self.internalMessage.fromId
            else:
                self.account_id = self.protocol.account_id
            try:
                for dc in listDC:
                    if dc in setUnique:
                        continue
                    setUnique.update((dc, ))
                    if not self.internalMessage:
                        for s, in session.query(
                                SBDB_ORM.Apartment_Relayer.relayer_id
                        ).join(SBDB_ORM.Apartment).join(
                                SBDB_ORM.ApartmentDevice).join(
                                    SBDB_ORM.Device).filter(
                                        and_(
                                            SBDB_ORM.Apartment.account_id ==
                                            self.account_id,
                                            SBDB_ORM.Device.uni_code ==
                                            dc.dev_code)).all():
                            print("tracing: ", s, self.account_id, dc.dev_code)
                            if s in self.dictWaitingRelayerControls:
                                self.dictWaitingRelayerControls[s].append(dc)
                            else:
                                self.dictWaitingRelayerControls[s] = [
                                    dc,
                                ]
                    else:
                        relayer_id = self.internalMessage.destId
                        if relayer_id in self.dictWaitingRelayerControls:
                            self.dictWaitingRelayerControls[relayer_id].append(
                                dc)
                        else:
                            self.dictWaitingRelayerControls[relayer_id] = [
                                dc,
                            ]
            except SQLAlchemyError as e:
                logging.error("transport %d:%s", id(self.protocol.transport),
                              e)
                session.rollback()
def LoadMapsFromDatabase():
    
    dictServerLoad.clear()
    dictClientServer.clear()
    dictSuperboxServer.clear()
    
    with SBDB.session_scope() as session :
        for client in session.query(SBDB_ORM.Client).filter(SBDB_ORM.Client.dt_active>datetime.datetime.now()-datetime.timedelta(seconds=Config.time_heartbeat)).all():
            item=CConnectionItem(client.server_id)
            item.dt_active=client.dt_active
            dictClientServer[client.id]=item
            dictServerLoad[item.server_id]=dictServerLoad.get(item.server_id,0)+1
        
        for superbox in session.query(SBDB_ORM.Superbox).filter(SBDB_ORM.Superbox.dt_active>datetime.datetime.now()-datetime.timedelta(seconds=Config.time_heartbeat)).all():
            item=CConnectionItem(superbox.server_id)
            item.dt_active=superbox.dt_active
            dictSuperboxServer[superbox.id]=item
            dictServerLoad[item.server_id]=dictServerLoad.get(item.server_id,0)+1
Exemplo n.º 25
0
def LoadMapsFromDatabase():
    
    dictServerLoad.clear()
    dictClientServer.clear()
    dictRelayerServer.clear()
    
    with SBDB.session_scope() as session :
        for client in session.query(SBDB_ORM.Client).filter(SBDB_ORM.Client.dt_active>datetime.datetime.now()-datetime.timedelta(seconds=Config.time_heartbeat)).all():
            item=CConnectionItem(client.server_id)
            item.dt_active=client.dt_active
            dictClientServer[client.id]=item
            dictServerLoad[item.server_id]=dictServerLoad.get(item.server_id,0)+1
        
        for relayer in session.query(SBDB_ORM.Relayer).filter(SBDB_ORM.Relayer.dt_active>datetime.datetime.now()-datetime.timedelta(seconds=Config.time_heartbeat)).all():
            item=CConnectionItem(relayer.server_id)
            item.dt_active=relayer.dt_active
            dictRelayerServer[relayer.id]=item
            dictServerLoad[item.server_id]=dictServerLoad.get(item.server_id,0)+1
Exemplo n.º 26
0
def RunOnlineMessage(message):
    global dictRelayerServer, dictClientServer, dictServerLoad, dictServerInfo,lockMaps
    with lockMaps:
        if len(message.destType)<2: return
        if(message.destType[1]==TTYPE_HUMAN):
            session_key=message.destId
            if message.operation==OPER_ONLINE:
                if not dictClientServer.has_key(session_key):    
                    dictServerLoad[message.fromId]=dictServerLoad.get(message.fromId,0)+1
                    dictClientServer[session_key]=CConnectionItem(message.fromId)
                else:
                    dictClientServer[session_key].server_id=message.fromId
                    dictClientServer[session_key].dt_active=datetime.datetime.now()
                if message.addition.lower()=='y':   #need redirect checking 
                    listRelayeres=SBDB.GetRelayeresByAccountId(message.fromId)
                    target_server_id=-1
                    for relayer_id in listRelayeres:                        
                        if dictRelayerServer.has_key(relayer_id):
                            #if there is a relayer connected to that account is connected on the same server with the account connection, don't redirect the account connection
                            if dictRelayerServer[relayer_id].server_id==message.fromId:
                                return
                            else:
                                target_server_id=relayer_id
                    if target_server_id>-1:
                        RedirectHumanTo(message.destId,target_server_id)
            elif message.operation==OPER_OFFLINE:
                if dictClientServer.has_key(session_key):    
                    dictServerLoad[message.fromId]=dictServerLoad.get(message.fromId,0)-1
                    dictClientServer.pop(session_key)
        elif(message.destType[1]==TTYPE_GATEWAY):
            if message.operation==OPER_ONLINE:
                if not dictRelayerServer.has_key(message.destId):    
                    dictServerLoad[message.fromId]=dictServerLoad.get(message.fromId,0)+1
                    dictRelayerServer[message.destId]=CConnectionItem(message.fromId)
                else:
                    dictRelayerServer[message.destId].server_id=message.fromId
                    dictRelayerServer[message.destId].dt_active=datetime.datetime.now()
            elif message.operation==OPER_OFFLINE:
                if dictRelayerServer.has_key(message.destId):    
                    dictServerLoad[message.fromId]=dictServerLoad.get(message.fromId,0)-1
                    dictRelayerServer.pop(message.destId)
        pass
Exemplo n.º 27
0
 def initByDeviceCmdList(self,listDC):
     self.DeviceKeyCode=""
     self.dictWaitingSuperboxControls={}
     setUnique=set()
     with SBDB.session_scope() as session :
         
         if self.internalMessage:
             self.account_id=self.internalMessage.fromId
         else:
             self.account_id=self.protocol.account_id
         try:
             for dc in listDC:
                 if dc in setUnique: continue
                 setUnique.update((dc,))
 #                 listSuperbox=[]
 #                 if not self.bTriedSuperboxMain:
 #                     s=session.query(SBDB_ORM.Superbox).join(SBDB_ORM.Apartment_Superbox).join(SBDB_ORM.Apartment).join(SBDB_ORM.Account).join(SBDB_ORM.ApartmentDevice).join(SBDB_ORM.Device).join(SBDB_ORM.DeviceModel).filter(and_(SBDB_ORM.Account.id==self.account_id,SBDB_ORM.Device.uni_code==dc.dev_code,SBDB_ORM.DeviceModel.name==dc.dev_model,SBDB_ORM.ApartmentDevice.superbox_id==SBDB_ORM.Superbox.id)).first()
 #                     if s:   listSuperbox.append(s)
 #                     self.bTriedSuperboxMain=True
 #                 if not self.internalMessage and len(listSuperbox)<=0:
 #                     listSuperboxId=[]
 #                     for s in session.query(SBDB_ORM.Superbox).join(SBDB_ORM.Apartment_Superbox).join(SBDB_ORM.Apartment).join(SBDB_ORM.Account).join(SBDB_ORM.ApartmentDevice).join(SBDB_ORM.Device).join(SBDB_ORM.DeviceModel).filter(and_(SBDB_ORM.Account.id==self.account_id,SBDB_ORM.Device.uni_code==dc.dev_code,SBDB_ORM.DeviceModel.name==dc.dev_model)):
 #                         if s.id not in listSuperboxId:
 #                             listSuperboxId.append(s.id)
 #                             listSuperbox.append(s)
 #                 for s in listSuperbox:
                 if not self.internalMessage:
                     for s, in session.query(distinct(SBDB_ORM.ApartmentDevice.superbox_id)).join(SBDB_ORM.Apartment).join(SBDB_ORM.Account).join(SBDB_ORM.Device).filter(and_(SBDB_ORM.Account.id==self.account_id,SBDB_ORM.Device.uni_code==dc.dev_code)).all():
                         #dc=listDC[listDC.index(dkc)]
                         if self.dictWaitingSuperboxControls.has_key(s):
                             self.dictWaitingSuperboxControls[s].append(dc)
                         else:
                             self.dictWaitingSuperboxControls[s]=[dc,]
                 else:
                     superbox_id=self.internalMessage.destId
                     if self.dictWaitingSuperboxControls.has_key(superbox_id):
                         self.dictWaitingSuperboxControls[superbox_id].append(dc)
                     else:
                         self.dictWaitingSuperboxControls[superbox_id]=[dc,]
         except SQLAlchemyError,e:
             logging.error("transport %d:%s",id(self.protocol.transport),e)
             session.rollback()
Exemplo n.º 28
0
 def Run(self):
     with self.protocol.lockCmd:
         if not self.Authorized(): 
             self.SendUnauthorizedResp()
             return
         CBaseCommand.Run(self)
         with SBDB.session_scope() as session :
             apartment_id=self.body[BaseCommand.PN_APARTMENTID]
             dev_id=self.body[BaseCommand.PN_DEVICEID]
             dev_code=self.body.get(BaseCommand.PN_DEVCODE,None)
             name=self.body.get(BaseCommand.PN_DEVNAME,None)
             flag_notification=self.body.get(BaseCommand.PN_FLAGNOTIFICATION,None)
             dev_keys=self.body.get(BaseCommand.PN_DEVKEYS,None)
             respond=self.GetResp()
             if dev_id is None:
                 respond.SetErrorCode(BaseCommand.CS_PARAMLACK)
             else:
                 try:
                     #SBDB.IncreaseVersion(session, self.protocol.account)
                     #superbox=session.query(SBDB_ORM.Superbox).join(SBDB_ORM.Device).filter(SBDB_ORM.Device.id==dev_id).first()
                     #apartment=SBDB.IncreaseVersions(session, superbox.id,apartment_id)
                     apartment=SBDB.IncreaseVersions(session, 0,apartment_id)
                     apartment_device=session.query(SBDB_ORM.ApartmentDevice).join(SBDB_ORM.Device).join(SBDB_ORM.Apartment).filter(and_(SBDB_ORM.Device.id==dev_id,SBDB_ORM.Apartment.id==apartment_id)).first()
                     if dev_code is not None: apartment_device.device.uni_code=dev_code 
                     if name is not None: apartment_device.name=name
                     if flag_notification is not None: apartment_device.flag_notification=flag_notification
                     if dev_keys is not None:
                         for dev_key in dev_keys:
                             for apartment_dev_key in apartment_device.apartment_device_keys:
                                 if apartment_dev_key.device_key_code.device_key.seq==dev_key[BaseCommand.PN_DEVSEQ]:
                                     if dev_key.has_key(BaseCommand.PN_NAME): apartment_dev_key.name=dev_key[BaseCommand.PN_NAME]
                                     if dev_key.has_key(BaseCommand.PN_DEVCODE): apartment_dev_key.device_key_code.uni_code=dev_key[BaseCommand.PN_DEVCODE]
                             #obj_device_key_code=session.query(SBDB_ORM.DeviceKeyCode).filter(and_(SBDB_ORM.DeviceKeyCode.device_id==device.id,SBDB_ORM.DeviceKeyCode.device_key_id==SBDB.GetDeviceKeyByModelAndSeq(device.device_model,dev_key[BaseCommand.PN_DEVSEQ]).id))
                             #if dev_key.has_key(BaseCommand.PN_NAME): obj_device_key_code.name=dev_key[BaseCommand.PN_NAME]
                             #if dev_key.has_key(BaseCommand.PN_DEVCODE): obj_device_key_code.uni_code=dev_key[BaseCommand.PN_DEVCODE]
                     respond.body[BaseCommand.PN_VERSION]=apartment.version
                     session.commit()
                 except SQLAlchemyError,e:
                     respond.SetErrorCode(BaseCommand.CS_DBEXCEPTION)
                     logging.error("transport %d:%s",id(self.protocol.transport),e)
                     session.rollback()
         respond.Send()
Exemplo n.º 29
0
 def Run(self):
     with self.protocol.lockCmd:
         if not self.Authorized(): 
             self.SendUnauthorizedResp()
             return
         CBaseCommand.Run(self)
         with SBDB.session_scope() as session :
             arm_state=self.body[BaseCommand.PN_ARMSTATE]
             apartment_id=self.body.get(BaseCommand.PN_APARTMENTID)
             respond=self.GetResp()
             try:
                 apartment=session.query(SBDB_ORM.Apartment).filter(SBDB_ORM.Apartment.id==apartment_id).first()
                 apartment.arm_state=arm_state
                 apartment.dt_arm=datetime.datetime.now()
                 session.commit()
                 self.PushToClients(session,apartment.dt_arm)
             except SQLAlchemyError,e:
                 respond.SetErrorCode(BaseCommand.CS_DBEXCEPTION)
                 logging.error("transport %d:%s",id(self.protocol.transport),e)
                 session.rollback()
         respond.Send()
Exemplo n.º 30
0
 def Run(self):
     with self.protocol.lockCmd:
         if not self.Authorized(): 
             self.SendUnauthorizedResp()
             return
         CBaseCommand.Run(self)
         with SBDB.session_scope() as session :
             arm_state=self.body[BaseCommand.PN_ARMSTATE]
             apartment_id=self.body.get(BaseCommand.PN_APARTMENTID)
             respond=self.GetResp()
             try:
                 apartment=session.query(SBDB_ORM.Apartment).filter(SBDB_ORM.Apartment.id==apartment_id).first()
                 apartment.arm_state=arm_state
                 apartment.dt_arm=datetime.datetime.now()
                 session.commit()
                 self.PushToClients(session,apartment.dt_arm)
             except SQLAlchemyError as e:
                 respond.SetErrorCode(BaseCommand.CS_DBEXCEPTION)
                 logging.error("transport %d:%s",id(self.protocol.transport),e)
                 session.rollback()
         respond.Send()
Exemplo n.º 31
0
 def Run(self):
     with self.protocol.lockCmd:
         if not self.Authorized(): 
             self.SendUnauthorizedResp()
             return
         CBaseCommand.Run(self)
         with SBDB.session_scope() as session :
             scene_id=self.body[BaseCommand.PN_SCENEID]
             name=self.body.get(BaseCommand.PN_SCENENAME)
             scene_contents=self.body.get(BaseCommand.PN_SCENECONTENTS)
             respond=self.GetResp()
             if scene_id is None:
                 respond.SetErrorCode(BaseCommand.CS_PARAMLACK)
             else:
                 try:
                     #SBDB.IncreaseVersion(session, self.protocol.account)
                     scene=session.query(SBDB_ORM.Scene).filter(SBDB_ORM.Scene.id==scene_id).first()
                     apartment=SBDB.IncreaseVersion(session, scene.apartment.id)
                     if name is not None: scene.name=name
                     modify_ids=set()
                     if scene_contents is not None:
                         for scene_content in scene_contents:
                             sc=session.query(SBDB_ORM.SceneContent).join(SBDB_ORM.Scene).join(SBDB_ORM.DeviceKeyCode).join(SBDB_ORM.DeviceKey).filter(and_(SBDB_ORM.Scene.id==scene_id,SBDB_ORM.DeviceKeyCode.device_id==scene_content[BaseCommand.PN_DEVICEID],SBDB_ORM.DeviceKey.seq==scene_content[BaseCommand.PN_DEVSEQ])).first()
                             if sc is None:
                                 sc=SBDB_ORM.SceneContent()
                                 sc.device_key_code_id,=session.query(SBDB_ORM.DeviceKeyCode.id).join(SBDB_ORM.DeviceKey).filter(and_(SBDB_ORM.DeviceKeyCode.device_id==scene_content[BaseCommand.PN_DEVICEID],SBDB_ORM.DeviceKey.seq==scene_content[BaseCommand.PN_DEVSEQ])).one()
                                 scene.scene_contents.append(sc)
                             else:
                                 modify_ids.update((sc.id,))
                             sc.value=scene_content[BaseCommand.PN_DEVVALUE]
                     for sc in scene.scene_contents:
                         if  sc.id is not None and sc.id not in modify_ids:    session.delete(sc)
                     
                     respond.body[BaseCommand.PN_VERSION]=apartment.version
                     session.commit()
                 except SQLAlchemyError,e:
                     respond.SetErrorCode(BaseCommand.CS_DBEXCEPTION)
                     logging.error("transport %d:%s",id(self.protocol.transport),e)
                     session.rollback()
         respond.Send()
Exemplo n.º 32
0
 def Run(self):
     with self.protocol.lockCmd:
         if not self.Authorized(): 
             self.SendUnauthorizedResp()
             return
         CBaseCommand.Run(self)
         apartment_id=self.body[BaseCommand.PN_APARTMENTID]
         sb_code=self.body[BaseCommand.PN_SB_CODE]
         sb_name=self.body[BaseCommand.PN_NAME]
         #account_id=self.protocol.account_id
         respond=self.GetResp()
         with SBDB.session_scope() as session :
             if session.query(SBDB_ORM.Superbox).join(SBDB_ORM.Apartment_Superbox).filter(and_(SBDB_ORM.Superbox.uni_code==sb_code,SBDB_ORM.Apartment_Superbox.apartment_id==apartment_id)).first() is not None:
                     respond.SetErrorCode(BaseCommand.CS_DEVICEEXIST)
             try:
                 superbox_id=SBDB.GetSuperboxIdForcely(sb_code)
                 apartment=SBDB.IncreaseVersion(session, apartment_id)
                 apartment_superbox=SBDB_ORM.Apartment_Superbox()
                 apartment_superbox.apartment_id=apartment_id
                 apartment_superbox.superbox_id=superbox_id
                 apartment_superbox.name=sb_name
                 '''
                 superbox=SBDB_ORM.Superbox()
                 superbox.apartment_id=apartment_id
                 superbox.name=sb_name
                 superbox.uni_code=sb_code            
                 session.add(superbox)
                 '''
                 session.add(apartment_superbox)
                 respond.body[BaseCommand.PN_VERSION]=apartment.version
                 session.commit()
 #                 if session.query(SBDB_ORM.Device).join(SBDB_ORM.Superbox).filter(SBDB_ORM.Superbox.id==superbox.id).first():
 #                     respond.body[BaseCommand.PN_UPDATEDATA]=True
                 respond.body[BaseCommand.PN_ID]=superbox_id
             except SQLAlchemyError,e:
                 respond.SetErrorCode(BaseCommand.CS_DBEXCEPTION)
                 logging.error("transport %d:%s",id(self.protocol.transport),e)
                 session.rollback()
         respond.Send()
         
Exemplo n.º 33
0
 def Run(self):
     with self.protocol.lockCmd:
         if not self.Authorized(): 
             self.SendUnauthorizedResp()
             return
         CBaseCommand.Run(self)
         with SBDB.session_scope() as session :
             dev_id=self.body[BaseCommand.PN_DEVICEID]
             apartment_id=self.body[BaseCommand.PN_APARTMENTID]
             dev_keys=self.body.get(BaseCommand.PN_DEVKEYS,None)
             respond=self.GetResp()
             if dev_id is None:
                 respond.SetErrorCode(BaseCommand.CS_PARAMLACK)
             else:
                 try:
                     #SBDB.IncreaseVersion(session, self.protocol.account)
                     #superbox=session.query(SBDB_ORM.Superbox).join(SBDB_ORM.Device).filter(SBDB_ORM.Device.id==dev_id).first()
                     apartment=SBDB.IncreaseVersions(session, 0,apartment_id)
                     if dev_keys is None:
                         session.query(SBDB_ORM.ApartmentDevice).join(SBDB_ORM.Apartment).join(SBDB_ORM.Device).filter(and_(SBDB_ORM.Apartment.id==apartment_id,SBDB_ORM.Device.id==dev_id)).delete()
                     else:
                         for dev_key in dev_keys:
                             session.delete(session.query(SBDB_ORM.ApartmentDeviceKey).join(SBDB_ORM.ApartmentDevice).join(SBDB_ORM.Apartment).join(SBDB_ORM.DeviceKeyCode).join(SBDB_ORM.DeviceKey).filter(and_(SBDB_ORM.Apartment.id==apartment_id,SBDB_ORM.DeviceKeyCode.device_id==dev_id,SBDB_ORM.DeviceKey.seq==dev_key[BaseCommand.PN_DEVSEQ])).first())                            
                         if session.query(SBDB_ORM.ApartmentDeviceKey).join(SBDB_ORM.ApartmentDevice).join(SBDB_ORM.Apartment).join(SBDB_ORM.DeviceKeyCode).filter(and_(SBDB_ORM.Apartment.id==apartment_id,SBDB_ORM.DeviceKeyCode.device_id==dev_id)).first() is None:
                             session.query(SBDB_ORM.ApartmentDevice).filter(and_(SBDB_ORM.ApartmentDevice.apartment_id==apartment_id,SBDB_ORM.ApartmentDevice.device_id==dev_id)).delete()
                             pass
                     respond.body[BaseCommand.PN_VERSION]=apartment.version
                     session.commit()
                     '''
                     SBDB.IncreaseVersion(session, self.protocol.account)
                     device=session.query(SBDB_ORM.Device).filter(SBDB_ORM.Device.id==dev_id).first()
                     device.deleted=True
                     respond.body[BaseCommand.PN_VERSION]=self.protocol.account.version
                     session.commit()
                     '''
                 except SQLAlchemyError,e:
                     respond.SetErrorCode(BaseCommand.CS_DBEXCEPTION)
                     logging.error("transport %d:%s",id(self.protocol.transport),e)
                     session.rollback()
         respond.Send()
 def Run(self):
     with self.protocol.lockCmd:
         if not self.Authorized(): 
             self.SendUnauthorizedResp()
             return
         CBaseCommand.Run(self)
         with SBDB.session_scope() as session :
             apartment_id=self.body[BaseCommand.PN_ID]
             respond=self.GetResp()
             if apartment_id is None:
                 respond.SetErrorCode(BaseCommand.CS_PARAMLACK)
             else:
                 try:
                     #SBDB.IncreaseVersion(session, self.protocol.account)
                     session.query(SBDB_ORM.Apartment).join(SBDB_ORM.Account,SBDB_ORM.Account.id==self.protocol.account_id).filter(SBDB_ORM.Apartment.id==apartment_id).delete()
                     respond.body[BaseCommand.PN_VERSION]=0
                     session.commit()
                 except SQLAlchemyError,e:
                     respond.SetErrorCode(BaseCommand.CS_DBEXCEPTION)
                     logging.error("transport %d:%s",id(self.protocol.transport),e)
                     session.rollback()
         respond.Send()
Exemplo n.º 35
0
 def Run(self):
     with self.protocol.lockCmd:
         if not self.Authorized(): 
             self.SendUnauthorizedResp()
             return
         CBaseCommand.Run(self)
         with SBDB.session_scope() as session :
             sb_id=self.body[BaseCommand.PN_SUPERBOXID]
             apartment_id=self.body[BaseCommand.PN_APARTMENTID]
             respond=self.GetResp()
             if sb_id is None:
                 respond.SetErrorCode(BaseCommand.CS_PARAMLACK)
             else:
                 try:
                     apartment=SBDB.IncreaseVersion(session, apartment_id)
                     session.query(SBDB_ORM.Apartment_Superbox).filter(and_(SBDB_ORM.Apartment_Superbox.superbox_id==sb_id,SBDB_ORM.Apartment_Superbox.apartment_id==apartment_id)).delete()
                     respond.body[BaseCommand.PN_VERSION]=apartment.version
                     session.commit()
                 except SQLAlchemyError,e:
                     respond.SetErrorCode(BaseCommand.CS_DBEXCEPTION)
                     logging.error("transport %d:%s",id(self.protocol.transport),e)
                     session.rollback()
         respond.Send()
Exemplo n.º 36
0
def SendAndSave(sms_template, apartment, alarm_type, listPhone,device_name):
    
    global mutex
    with mutex:
        
        #message,result,error=SendAlarmBySMS(sms_template,apartment.name,alarm_type,listPhone,device_name)
        message,result,error=SendAlarmBySMS(sms_template,apartment.account.user_name,alarm_type,listPhone,device_name)
        
        #insert into database
        sms_head=SBDB_ORM.SmsSenderHead()
        sms_head.apartment_id=apartment.id
        sms_head.content=message
        sms_head.dt=datetime.datetime.now()
        for phone in listPhone:
            sms_list=SBDB_ORM.SmsSenderList()
            sms_list.mobile_phone=phone
            sms_list.result=error
            sms_head.sms_sender_lists.append(sms_list)
            
        with SBDB.session_scope() as session :
            session.add(sms_head)
            session.commit()
        return result
Exemplo n.º 37
0
    def Run(self):
        with self.protocol.lockCmd:
            CBaseCommand.Run(self)
            with SBDB.session_scope() as session:
                respond = self.GetResp()
                email = self.body.get(BaseCommand.PN_EMAIL, None)
                account_id, = session.query(SBDB_ORM.Account.id).filter(
                    SBDB_ORM.Account.email == email).first()
                if email is None:
                    respond.SetErrorCode(BaseCommand.CS_NOTFOUNDEMAIL)
                elif account_id is None:
                    respond.SetErrorCode(BaseCommand.CS_NOTFOUNDEMAIL)

    #             elif 'dt_restore_require' in dir(self.protocol) and (datetime.datetime.now()-self.protocol.dt_restore_require).seconds<Config.second_restore_require:
    #                 respond.SetErrorCode(BaseCommand.CS_TRYLATER)
                else:
                    try:
                        content = open(
                            os.path.join(Config.dir_local_static,
                                         "restore_confirm.html"), 'r').read()
                        url = Util.GenRestoreURL(account_id)
                        content = content.replace("{{url_restore}}", url)
                        #emaillib.SendEmail("Honeywell Smart Home: reset password confirm", content, [self.protocol.account.email])
                        threading.Thread(
                            target=emaillib.SendEmail,
                            args=(
                                "Honeywell Smart Home: reset password confirm",
                                content, [email]),
                            daemon=True).start()
                        self.protocol.dt_restore_require = datetime.datetime.now(
                        )
                    except SQLAlchemyError as e:
                        respond.SetErrorCode(BaseCommand.CS_DBEXCEPTION)
                        logging.error("transport %d:%s",
                                      id(self.protocol.transport), e)
                        session.rollback()
            respond.Send()
Exemplo n.º 38
0
 def Run(self):
     with self.protocol.lockCmd:
         if not self.Authorized(): 
             self.SendUnauthorizedResp()
             return
         CBaseCommand.Run(self)
         with SBDB.session_scope() as session :
             version=self.body[BaseCommand.PN_VERSION]
             apartment_id=self.body[BaseCommand.PN_APARTMENTID]
             respond=self.GetResp()
             try:
                 apartment=session.query(SBDB_ORM.Apartment).filter(SBDB_ORM.Apartment.id==apartment_id).one()
                 respond.body[BaseCommand.PN_VERSION]=apartment.version
                 respond.body[BaseCommand.PN_SCENE_ID]=apartment.scene_id
                 respond.body[BaseCommand.PN_ARMSTATE]=apartment.arm_state
                 if version!=apartment.version:
                     apartment_info={}
                     apartment_info[BaseCommand.PN_ID]=apartment.id
                     apartment_info[BaseCommand.PN_NAME]=apartment.name
                     apartment_info[BaseCommand.PN_VERSION]=apartment.version
                     
                     bDeviceInserted=False
                     listDevice=[]
                     for apartment_device in apartment.apartment_devices:
                         elementDevice={}
                         elementDevice[BaseCommand.PN_ID]=apartment_device.device.id
                         elementDevice[BaseCommand.PN_DEVTYPE]=apartment_device.device.device_model.device_type.name
                         elementDevice[BaseCommand.PN_DEVMODEL]=apartment_device.device.device_model.name
                         elementDevice[BaseCommand.PN_DEVCODE]=apartment_device.device.uni_code
                         elementDevice[BaseCommand.PN_DEVNAME]=apartment_device.name
                         listDeviceKey=[]
                         for apartmentDeviceKey in apartment_device.apartment_device_keys:
                             elementDeviceKey={}
                             elementDeviceKey[BaseCommand.PN_DEVSEQ]=apartmentDeviceKey.device_key_code.device_key.seq
                             elementDeviceKey[BaseCommand.PN_NAME]=apartmentDeviceKey.name
                             listDeviceKey.append(elementDeviceKey)
                         elementDevice[BaseCommand.PN_DEVICEKEYS]=listDeviceKey
                         listDevice.append(elementDevice)
 
                     listSuperbox=[]
                     for apartment_superbox in apartment.apartment_superboxs:
                         superbox=apartment_superbox.superbox
                         elementSuperbox={}
                         elementSuperbox[BaseCommand.PN_ID]=superbox.id
                         elementSuperbox[BaseCommand.PN_SB_CODE]=superbox.uni_code
 #                         listDevice=[]
 #                         for device in superbox.devices:
 #                             elementDevice={}
 #                             elementDevice[BaseCommand.PN_ID]=device.id
 #                             elementDevice[BaseCommand.PN_DEVTYPE]=device.device_model.device_type.name
 #                             elementDevice[BaseCommand.PN_DEVMODEL]=device.device_model.name
 #                             elementDevice[BaseCommand.PN_DEVCODE]=device.uni_code
 #                             elementDevice[BaseCommand.PN_DEVNAME]=device.name
 #                             listDeviceKey=[]
 #                             for deviceKeyCode in device.device_key_codes:
 #                                 elementDeviceKey={}
 #                                 elementDeviceKey[BaseCommand.PN_DEVSEQ]=deviceKeyCode.device_key.seq
 #                                 elementDeviceKey[BaseCommand.PN_NAME]=deviceKeyCode.name
 #                                 listDeviceKey.append(elementDeviceKey)
 #                             elementDevice[BaseCommand.PN_DEVICEKEYS]=listDeviceKey
 #                             listDevice.append(elementDevice)
                         if not bDeviceInserted:
                             elementSuperbox[BaseCommand.PN_DEVICES]=listDevice
                             bDeviceInserted=True
                         listSuperbox.append(elementSuperbox)
                     apartment_info[BaseCommand.PN_SUPERBOXS]=listSuperbox
                     
                     listScene=[]
                     for scene in apartment.scenes:
                         elementScene={}
                         elementScene[BaseCommand.PN_ID]=scene.id
                         elementScene[BaseCommand.PN_NAME]=scene.name
                         listSceneContent=[]
                         for scene_content in scene.scene_contents:
                             elementSceneContent={}
                             elementSceneContent[BaseCommand.PN_ID]=scene_content.id
                             elementSceneContent[BaseCommand.PN_DEVICEID]=scene_content.device_key_code.device.id
                             elementSceneContent[BaseCommand.PN_DEVSEQ]=scene_content.device_key_code.device_key.seq
                             elementSceneContent[BaseCommand.PN_DEVVALUE]=scene_content.value
                             listSceneContent.append(elementSceneContent)
                         elementScene[BaseCommand.PN_SCENECONTENTS]=listSceneContent
                         listScene.append(elementScene)
                     apartment_info[BaseCommand.PN_SCENES]=listScene
                     
                     listContactor=[]
                     for contactor in apartment.contactors:
                         elementContactor={}
                         elementContactor[BaseCommand.PN_ID]=contactor.id
                         elementContactor[BaseCommand.PN_NAME]=contactor.name
                         elementContactor[BaseCommand.PN_MOBLEPHONE]=contactor.mobile_phone
                         listContactor.append(elementContactor)
                     apartment_info[BaseCommand.PN_CONTACTORS]=listContactor
                     
                     respond.body[BaseCommand.PN_APARTMENTINFO]=apartment_info
                     
             except SQLAlchemyError,e:
                 respond.SetErrorCode(BaseCommand.CS_DBEXCEPTION)
                 logging.error("transport %d:%s",id(self.protocol.transport),e)
                 session.rollback()
         respond.Send()
Exemplo n.º 39
0
 def Run(self):
     with self.protocol.lockCmd:
         CBaseCommand.Run(self)
         if 'role' in dir(self.protocol):
             self.protocol.releaseFromDict()
         role=self.body[BaseCommand.PN_TERMINALTYPE]
         resp=self.GetResp()
         resp.body[BaseCommand.PN_RESULT]=BaseCommand.PV_E_OK
         if cmp(role,BaseCommand.PV_ROLE_SUPERBOX)==0:
             sb_code=self.body[BaseCommand.PN_SB_CODE]
             self.protocol.superbox_id=SBDB.GetSuperboxIdForcely(sb_code)
             self.protocol.role=role
             with self.protocol.factory.lockDict:
                 self.protocol.factory.dictSuperbox[self.protocol.superbox_id]=self.protocol
             #logging.info("transport %d: superbox %s login pass",id(self.protocol.transport),sb_code)
             threads.deferToThread(SBDB.UpdateAuthTimeSuperbox,self.protocol.superbox_id)
         elif cmp(role,BaseCommand.PV_ROLE_HUMAN)==0:
             #self.protocol.account=SBDB.GetAccount(self.body[BaseCommand.PN_USERNAME], self.body[BaseCommand.PN_PASSWORD])
             with SBDB.session_scope() as session :
                 account=SBDB.GetAccount(session,self.body[BaseCommand.PN_USERNAME])
                 if account is not None and not Util.check_password(self.body[BaseCommand.PN_PASSWORD], account.password) :
                     account=None
                 if account is None:
                     resp.body[BaseCommand.PN_RESULT]=BaseCommand.PV_E_USERPASS
                     resp.body[BaseCommand.PN_ERRORSTRING]="user/password mismatch"
                     resp.SetErrorCode(BaseCommand.CS_LOGINFAIL)
                 else:
                     self.protocol.account_id=account.id
                     self.protocol.role=role
                     self.protocol.client_id=-1
                     self.protocol.rcv_alarm=self.body.get(BaseCommand.PN_RCVALARM,"False")
                     listApartment=[]
                     for apartment in account.apartments:
                         elementApartment={}
                         elementApartment[BaseCommand.PN_ID]=apartment.id
                         listApartment.append(elementApartment)
                     resp.body[BaseCommand.PN_APARTMENTS]=listApartment
                     dictAccount=self.protocol.factory.dictAccounts
                     for superboxId in SBDB.GetSuperboxIDsByAccountId(self.protocol.account_id):
                         with self.protocol.factory.lockDict:
                             if dictAccount.has_key(superboxId):
                                 dictAccount[superboxId].append(self.protocol)
                             else:
                                 dictAccount[superboxId]=[self.protocol,]
                     
                     #set client information
                     os=self.body.get(BaseCommand.PN_OS,BaseCommand.PV_OS_IOS)
                     token=self.body.get(BaseCommand.PN_TOKEN)
                     last_token=self.body.get(BaseCommand.PN_LASTTOKEN)
                     balance=self.body.get(BaseCommand.PN_BALANCE)
                     #terminal_code=self.body.get(BaseCommand.PN_TERMINALCODE,datetime.datetime.now().strftime("%Y%m%d%H%M%S")+str(random.uniform(0,4000)))
                     if token=='' or token is None:
                         terminal_code=self.body.get(BaseCommand.PN_TERMINALCODE,datetime.datetime.now().strftime("%Y%m%d%H%M%S")+str(random.uniform(0,4000)))
                     else:
                         terminal_code=self.body.get(BaseCommand.PN_TERMINALCODE,token)
                     
                     try:
                         ###for temply use
                         if token is not None:
                             session.query(SBDB_ORM.Client).filter(and_(SBDB_ORM.Client.account_id!=self.protocol.account_id,SBDB_ORM.Client.device_token==token.strip())).delete()
                         ###-------------
                         if last_token is not None and token <> last_token:
                             #session.query(SBDB_ORM.Client).filter(and_(SBDB_ORM.Client.account_id==self.protocol.account_id,SBDB_ORM.Client.device_token==last_token.strip())).delete()
                             session.query(SBDB_ORM.Client).filter(SBDB_ORM.Client.device_token==last_token.strip()).delete()
                         
                         client=session.query(SBDB_ORM.Client).filter(SBDB_ORM.Client.terminal_code==terminal_code.strip()).first()
                         if client is None:
                             if token is not None:   session.query(SBDB_ORM.Client).filter(SBDB_ORM.Client.device_token==token.strip()).delete()
                             client=SBDB_ORM.Client()
                             client.device_token=token
                             client.enable_alarm=True
                             client.os=os
                             session.add(client)
                         client.account_id=self.protocol.account_id
                         client.terminal_code=terminal_code
                         client.dt_auth=client.dt_active=datetime.datetime.now() 
                         client.server_id=InternalMessage.MyServerID                       
                         session.commit()
                         self.protocol.client_id=client.id
                         #logging.info("transport %d: user %s login pass ",id(self.protocol.transport),self.body[BaseCommand.PN_USERNAME])
                         if balance is None: balance='n'
                         threads.deferToThread(SBDB.UpdateAuthTimeHuman,client.id,balance,id(self.protocol.transport))
                     except SQLAlchemyError,e:
                         resp.SetErrorCode(BaseCommand.CS_DBEXCEPTION)
                         logging.error("transport %d:%s",id(self.protocol.transport),e)
                         session.rollback()
                 
         else:
Exemplo n.º 40
0
    def Run(self):
        with self.protocol.lockCmd:
            if not self.Authorized():
                self.SendUnauthorizedResp()
                return
            CBaseCommand.Run(self)
            with SBDB.session_scope() as session:
                version = self.body[BaseCommand.PN_VERSION]
                apartment_id = self.body[BaseCommand.PN_APARTMENTID]
                respond = self.GetResp()
                try:
                    apartment = session.query(SBDB_ORM.Apartment).filter(
                        SBDB_ORM.Apartment.id == apartment_id).one()
                    respond.body[BaseCommand.PN_VERSION] = apartment.version
                    respond.body[BaseCommand.PN_SCENE_ID] = apartment.scene_id
                    respond.body[BaseCommand.PN_ARMSTATE] = apartment.arm_state
                    if version != apartment.version:
                        apartment_info = {}
                        apartment_info[BaseCommand.PN_ID] = apartment.id
                        apartment_info[BaseCommand.PN_NAME] = apartment.name
                        apartment_info[
                            BaseCommand.PN_VERSION] = apartment.version

                        bDeviceInserted = False
                        listDevice = []
                        for apartment_device in apartment.apartment_devices:
                            elementDevice = {}
                            elementDevice[
                                BaseCommand.PN_ID] = apartment_device.device.id
                            elementDevice[
                                BaseCommand.
                                PN_DEVTYPE] = apartment_device.device.device_model.device_type.name
                            elementDevice[
                                BaseCommand.
                                PN_DEVMODEL] = apartment_device.device.device_model.name
                            elementDevice[
                                BaseCommand.
                                PN_DEVCODE] = apartment_device.device.uni_code
                            elementDevice[
                                BaseCommand.PN_DEVNAME] = apartment_device.name
                            listDeviceKey = []
                            listDevice.append(elementDevice)

                        listRelayer = []
                        for apartment_relayer in apartment.apartment_relayers:
                            relayer = apartment_relayer.relayer
                            elementRelayer = {}
                            elementRelayer[BaseCommand.PN_ID] = relayer.id
                            elementRelayer[
                                BaseCommand.PN_SB_CODE] = relayer.uni_code
                            if not bDeviceInserted:
                                elementRelayer[
                                    BaseCommand.PN_DEVICES] = listDevice
                                bDeviceInserted = True
                            listRelayer.append(elementRelayer)
                        apartment_info[BaseCommand.PN_RELAYERS] = listRelayer

                        respond.body[
                            BaseCommand.PN_APARTMENTINFO] = apartment_info

                except SQLAlchemyError, e:
                    respond.SetErrorCode(BaseCommand.CS_DBEXCEPTION)
                    logging.error("transport %d:%s",
                                  id(self.protocol.transport), e)
                    session.rollback()
            respond.Send()
Exemplo n.º 41
0
    def FinishOne(self, relayer_id, control_device, respond):
        with self.lock:
            # deviceCmds=self.dictSendingRelayerControls.get(relayer)
            deviceCmds = None
            for key in self.dictSendingRelayerControls.keys():
                if key == relayer_id:
                    deviceCmds = self.dictSendingRelayerControls[key]
            if deviceCmds is not None:
                for deviceCmd in deviceCmds:
                    if control_device.body[
                            BaseCommand.
                            PN_DEVMODEL] == deviceCmd.dev_model and control_device.body[
                                BaseCommand.
                                PN_DEVCODE] == deviceCmd.dev_code and control_device.body[
                                    BaseCommand.
                                    PN_DEVSEQ] == deviceCmd.dev_seq:
                        if deviceCmd.result != 0:
                            deviceCmd.result = respond.command_status
                            deviceCmd.body = respond.body

                            # if it's failed, and have not try other relayer in the same account: add these relayer to dictWaitingRelayerControls
                            if deviceCmd.result != 0 and not deviceCmd.bTriedRelayerMain and self.protocol.role == BaseCommand.PV_ROLE_HUMAN:
                                with SBDB.session_scope() as session:
                                    deviceCmd.bTriedRelayerMain = True

                                    listRelayerId = []
                                    for s in session.query(
                                            SBDB_ORM.Relayer
                                    ).join(SBDB_ORM.Apartment_Relayer).join(
                                            SBDB_ORM.Apartment
                                    ).join(SBDB_ORM.Account).join(
                                            SBDB_ORM.ApartmentDevice
                                    ).join(SBDB_ORM.Device).join(
                                            SBDB_ORM.DeviceModel).filter(
                                                and_(
                                                    SBDB_ORM.Account.id ==
                                                    self.protocol.account_id,
                                                    SBDB_ORM.Device.uni_code ==
                                                    deviceCmd.dev_code,
                                                    SBDB_ORM.DeviceModel.name
                                                    == deviceCmd.dev_model,
                                                    SBDB_ORM.Relayer.id !=
                                                    relayer_id)):
                                        if s.id not in listRelayerId:
                                            listRelayerId.append(s.id)
                                    if len(listRelayerId) > 0:
                                        deviceCmd.result = -1
                                        deviceCmds.remove(deviceCmd)
                                        for s in listRelayerId:
                                            print("relayer:", s)
                                            if s in self.dictWaitingRelayerControls:
                                                self.dictWaitingRelayerControls[
                                                    s].append(deviceCmd)
                                            else:
                                                self.dictWaitingRelayerControls[
                                                    s] = [
                                                        deviceCmd,
                                                    ]

                        # if it's succeed finished by other relayer, set this relayer as this device's mainSueprbox
                        if deviceCmd.result == 0 and deviceCmd.bTriedRelayerMain:
                            with SBDB.session_scope() as session:
                                for apartment_device in session.query(
                                        SBDB_ORM.ApartmentDevice
                                ).join(SBDB_ORM.Device).join(
                                        SBDB_ORM.Apartment).join(
                                            SBDB_ORM.Account).filter(
                                                and_(
                                                    SBDB_ORM.Account.id ==
                                                    self.protocol.account_id,
                                                    SBDB_ORM.Device.uni_code ==
                                                    deviceCmd.dev_code)):
                                    apartment_device.relayer_id = relayer_id
                                session.commit()
                        break
            self.FeedbackIfFinished()
Exemplo n.º 42
0
    def initDictSuperboxControls(self):
        special_scene=self.body.get(BaseCommand.PN_SPECIALSCENE,BaseCommand.PV_SCENE_SPECIFIED)
        with SBDB.session_scope() as session :
            try:
                session.expire_on_commit = False
                if special_scene==BaseCommand.PV_SCENE_GASSENSOR:
                    apartment_id=self.body[BaseCommand.PN_APARTMENTID]
                    for superbox in session.query(SBDB_ORM.Superbox).join(SBDB_ORM.Apartment_Superbox).filter(SBDB_ORM.Apartment_Superbox.apartment_id==apartment_id).all():
                        with self.protocol.factory.lockDict:
                            sb_protocol=self.protocol.factory.dictSuperbox.get(superbox.id)
                        if sb_protocol is None:
                            continue
                        request=ControlDevice.CControlDevice(protocol=sb_protocol)
                        request.body[BaseCommand.PN_DEVMODEL]=BaseCommand.gas_actuator_model
                        request.body[BaseCommand.PN_DEVCODE]="00"
                        request.body[BaseCommand.PN_DEVSEQ]=0                    
                        request.body[BaseCommand.PN_DEVVALUE]=1   
                        request.Send()
                if special_scene==BaseCommand.PV_SCENE_ALLLIGHTON:
                    apartment_id=self.body[BaseCommand.PN_APARTMENTID]
                    listDeviceCmd=[]    
                    for device,device_key,device_state, in SBDB.GetLightsByApartmentID(session,apartment_id,"on"):
                    #for device,device_key,device_state, in session.query(SBDB_ORM.Device,SBDB_ORM.DeviceKey,SBDB_ORM.DeviceState).join(SBDB_ORM.ApartmentDevice).join(SBDB_ORM.Apartment).join(SBDB_ORM.DeviceModel).filter(and_(SBDB_ORM.Device.id==SBDB_ORM.DeviceKeyCode.device_id,SBDB_ORM.DeviceKeyCode.device_key_id==SBDB_ORM.DeviceKey.id,SBDB_ORM.DeviceKey.id==SBDB_ORM.DeviceState.device_key_id,SBDB_ORM.DeviceState.name=="on",SBDB_ORM.Apartment.id==apartment_id,SBDB_ORM.Device.device_model_id==SBDB_ORM.DeviceModel.id,SBDB_ORM.DeviceModel.device_type_id==SBDB_ORM.DeviceType.id,SBDB_ORM.DeviceType.name.like('%light%'))).options(undefer(SBDB_ORM.Device.id)):
                        if device not in session:
                            device = session.query(SBDB_ORM.Device).get(device.id)
                        listDeviceCmd.append(CDeviceCmd(device.device_model.name, \
                                      device.uni_code, \
                                      device_key.seq, \
                                      device_state.value_end))
                        self.initByDeviceCmdList(listDeviceCmd)
                elif special_scene==BaseCommand.PV_SCENE_ALLLIGHTOFF:
                    apartment_id=self.body[BaseCommand.PN_APARTMENTID]
                    listDeviceCmd=[]    
                    for device,device_key,device_state, in SBDB.GetLightsByApartmentID(session,apartment_id,"off"):
                        if device not in session:
                            device = session.query(SBDB_ORM.Device).get(device.id)
                        listDeviceCmd.append(CDeviceCmd(device.device_model.name, \
                                      device.uni_code, \
                                      device_key.seq, \
                                      device_state.value_end))
                        self.initByDeviceCmdList(listDeviceCmd)
                else:
                    scene_id=self.body[BaseCommand.PN_ID]
                    listDeviceCmd=[]                
                    for scene_content in session.query(SBDB_ORM.SceneContent).filter(SBDB_ORM.SceneContent.scene_id==scene_id).all():
                        listDeviceCmd.append(CDeviceCmd(scene_content.device_key_code.device_key.device_model.name, \
                                      scene_content.device_key_code.device.uni_code, \
                                      scene_content.device_key_code.device_key.seq, \
                                      scene_content.value))
                    self.initByDeviceCmdList(listDeviceCmd)
                
                if special_scene in (BaseCommand.PV_SCENE_ALLLIGHTOFF,BaseCommand.PV_SCENE_ALLLIGHTON):
                    self.bFinished=True
                    self.SendResp()
                    
                            
                    '''
                    setDeviceCmd=set()
                    for device in session.query(SBDB_ORM.Device).join(SBDB_ORM.DeviceModel).filter(SBDB_ORM.DeviceModel.name==BaseCommand.gas_actuator_model).join(SBDB_ORM.Superbox).join(SBDB_ORM.Apartment_Superbox).filter(SBDB_ORM.Apartment_Superbox.apartment_id==apartment_id):
                        deviceCmd=CDeviceCmd(BaseCommand.gas_actuator_model,device.uni_code,0,BaseCommand.gas_actuator_value)
                        if deviceCmd in self.EventGas.setControlCmd:    continue
                        if deviceCmd not in setDeviceCmd: setDeviceCmd.update((deviceCmd,))
                        self.EventGas.setControlCmd.update((deviceCmd,))
                    listDeviceCmd=list(setDeviceCmd)
                    self.initByDeviceCmdList(listDeviceCmd)
                    '''
#             except SQLAlchemyError,e:
#                     logging.error("transport %d:%s",id(self.protocol.transport),e)
#                     session.rollback()
#                     raise e
            finally:
                pass
Exemplo n.º 43
0
    def Run(self):
        with self.protocol.lockCmd:
            CBaseCommand.Run(self)
            if 'role' in dir(self.protocol):
                self.protocol.releaseFromDict()
            role = self.body[BaseCommand.PN_TERMINALTYPE]
            resp = self.GetResp()
            resp.body[BaseCommand.PN_RESULT] = BaseCommand.PV_E_OK
            if cmp(role, BaseCommand.PV_ROLE_RELAYER) == 0:
                sb_code = self.body[BaseCommand.PN_SB_CODE]
                self.protocol.relayer_id = SBDB.GetRelayerIdForcely(sb_code)
                self.protocol.role = role
                with self.protocol.factory.lockDict:
                    self.protocol.factory.dictRelayer[
                        self.protocol.relayer_id] = self.protocol
                #logging.info("transport %d: relayer %s login pass",id(self.protocol.transport),sb_code)
                threads.deferToThread(SBDB.UpdateAuthTimeRelayer,
                                      self.protocol.relayer_id)
            elif cmp(role, BaseCommand.PV_ROLE_HUMAN) == 0:
                #self.protocol.account=SBDB.GetAccount(self.body[BaseCommand.PN_USERNAME], self.body[BaseCommand.PN_PASSWORD])
                with SBDB.session_scope() as session:
                    account = SBDB.GetAccount(
                        session, self.body[BaseCommand.PN_USERNAME])
                    if account is not None and not Util.check_password(
                            self.body[BaseCommand.PN_PASSWORD],
                            account.password):
                        account = None
                    if account is None:
                        resp.body[
                            BaseCommand.PN_RESULT] = BaseCommand.PV_E_USERPASS
                        resp.body[BaseCommand.
                                  PN_ERRORSTRING] = "user/password mismatch"
                        resp.SetErrorCode(BaseCommand.CS_LOGINFAIL)
                    else:
                        self.protocol.account_id = account.id
                        self.protocol.role = role
                        self.protocol.client_id = -1
                        self.protocol.rcv_alarm = self.body.get(
                            BaseCommand.PN_RCVALARM, "False")
                        listApartment = []
                        for apartment in account.apartments:
                            elementApartment = {}
                            elementApartment[BaseCommand.PN_ID] = apartment.id
                            listApartment.append(elementApartment)
                        resp.body[BaseCommand.PN_APARTMENTS] = listApartment
                        dictAccount = self.protocol.factory.dictAccounts
                        for relayerId in SBDB.GetRelayerIDsByAccountId(
                                self.protocol.account_id):
                            with self.protocol.factory.lockDict:
                                if dictAccount.has_key(relayerId):
                                    dictAccount[relayerId].append(
                                        self.protocol)
                                else:
                                    dictAccount[relayerId] = [
                                        self.protocol,
                                    ]

                        #set client information
                        os = self.body.get(BaseCommand.PN_OS,
                                           BaseCommand.PV_OS_IOS)
                        token = self.body.get(BaseCommand.PN_TOKEN)
                        last_token = self.body.get(BaseCommand.PN_LASTTOKEN)
                        balance = self.body.get(BaseCommand.PN_BALANCE)
                        #terminal_code=self.body.get(BaseCommand.PN_TERMINALCODE,datetime.datetime.now().strftime("%Y%m%d%H%M%S")+str(random.uniform(0,4000)))
                        if token == '' or token is None:
                            terminal_code = self.body.get(
                                BaseCommand.PN_TERMINALCODE,
                                datetime.datetime.now().strftime(
                                    "%Y%m%d%H%M%S") +
                                str(random.uniform(0, 4000)))
                        else:
                            terminal_code = self.body.get(
                                BaseCommand.PN_TERMINALCODE, token)

                        try:
                            ###for temply use
                            if token is not None:
                                session.query(SBDB_ORM.Client).filter(
                                    and_(
                                        SBDB_ORM.Client.account_id !=
                                        self.protocol.account_id,
                                        SBDB_ORM.Client.device_token ==
                                        token.strip())).delete()
                            ###-------------
                            if last_token is not None and token <> last_token:
                                #session.query(SBDB_ORM.Client).filter(and_(SBDB_ORM.Client.account_id==self.protocol.account_id,SBDB_ORM.Client.device_token==last_token.strip())).delete()
                                session.query(SBDB_ORM.Client).filter(
                                    SBDB_ORM.Client.device_token ==
                                    last_token.strip()).delete()

                            client = session.query(SBDB_ORM.Client).filter(
                                SBDB_ORM.Client.terminal_code ==
                                terminal_code.strip()).first()
                            if client is None:
                                if token is not None:
                                    session.query(SBDB_ORM.Client).filter(
                                        SBDB_ORM.Client.device_token ==
                                        token.strip()).delete()
                                client = SBDB_ORM.Client()
                                client.device_token = token
                                client.enable_alarm = True
                                client.os = os
                                session.add(client)
                            client.account_id = self.protocol.account_id
                            client.terminal_code = terminal_code
                            client.dt_auth = client.dt_active = datetime.datetime.now(
                            )
                            client.server_id = InternalMessage.MyServerID
                            session.commit()
                            self.protocol.client_id = client.id
                            #logging.info("transport %d: user %s login pass ",id(self.protocol.transport),self.body[BaseCommand.PN_USERNAME])
                            if balance is None: balance = 'n'
                            threads.deferToThread(SBDB.UpdateAuthTimeHuman,
                                                  client.id, balance,
                                                  id(self.protocol.transport))
                        except SQLAlchemyError, e:
                            resp.SetErrorCode(BaseCommand.CS_DBEXCEPTION)
                            logging.error("transport %d:%s",
                                          id(self.protocol.transport), e)
                            session.rollback()

            else:
Exemplo n.º 44
0
    def Run(self):
        with self.protocol.lockCmd:
            if not self.Authorized():
                self.SendUnauthorizedResp()
                return
            CBaseCommand.Run(self)

            apartment_id = self.body[BaseCommand.PN_APARTMENTID]
            relayer_id = self.body.get(BaseCommand.PN_RELAYERID)
            dev_model = self.body[BaseCommand.PN_DEVMODEL]
            dev_code = self.body[BaseCommand.PN_DEVCODE]
            dev_keys = self.body.get(BaseCommand.PN_DEVKEYS)
            respond = self.GetResp()
            with SBDB.session_scope() as session:
                model = SBDB.GetDeviceModelByName(session, dev_model)
                try:
                    if relayer_id is None:
                        relayer_id, = session.query(SBDB_ORM.Relayer.id).join(
                            SBDB_ORM.Apartment_Relayer).filter(
                                SBDB_ORM.Apartment_Relayer.apartment_id ==
                                apartment_id).order_by(
                                    SBDB_ORM.Relayer.id).first()
                    else:
                        relayer_id = int(relayer_id)
                    if model is None:
                        respond.SetErrorCode(BaseCommand.CS_DEVICEMODEL)
                    elif relayer_id is None:
                        respond.SetErrorCode(BaseCommand.CS_NORELAYER)
                    elif session.query(SBDB_ORM.ApartmentDevice).join(
                            SBDB_ORM.Device).filter(
                                and_(
                                    SBDB_ORM.Device.uni_code == dev_code,
                                    SBDB_ORM.ApartmentDevice.apartment_id ==
                                    apartment_id)).first() is not None:
                        respond.SetErrorCode(BaseCommand.CS_DEVICEEXIST)
                    else:
                        apartment = SBDB.IncreaseVersions(
                            session, 0, apartment_id)
                        device = SBDB.GetDeviceForcely(session, dev_code,
                                                       dev_model)
                        if device is None:
                            device = SBDB_ORM.Device()
                            device.device_model_id = model.id
                            device.uni_code = dev_code

                            session.add(device)

                        else:
                            apartment_device = SBDB_ORM.ApartmentDevice()
                            apartment_device.apartment_id = apartment_id
                            apartment_device.name = model.device_type.name
                            apartment_device.relayer_id = relayer_id
                            apartment_device.device_id = device.id

                            respond.body[
                                BaseCommand.PN_VERSION] = apartment.version
                            session.add(apartment_device)
                            session.commit()
                            respond.body[BaseCommand.PN_DEVICEID] = device.id
                except SQLAlchemyError, e:
                    respond.SetErrorCode(BaseCommand.CS_DBEXCEPTION)
                    logging.error("transport %d:%s",
                                  id(self.protocol.transport), e)
                    session.rollback()
            respond.Send()
Exemplo n.º 45
0
 def Run(self):
     with self.protocol.lockCmd:
         if not self.Authorized(): 
             self.SendUnauthorizedResp()
             return
         CBaseCommand.Run(self)
         
         apartment_id=self.body[BaseCommand.PN_APARTMENTID]
         superbox_id=self.body.get(BaseCommand.PN_SUPERBOXID)
         dev_model=self.body[BaseCommand.PN_DEVMODEL]
         dev_code=self.body[BaseCommand.PN_DEVCODE]
         dev_keys=self.body.get(BaseCommand.PN_DEVKEYS)
         respond=self.GetResp()
         with SBDB.session_scope() as session :
             model=SBDB.GetDeviceModelByName(session,dev_model)
             try:
                 if superbox_id is None:
                     superbox_id,=session.query(SBDB_ORM.Superbox.id).join(SBDB_ORM.Apartment_Superbox).filter(SBDB_ORM.Apartment_Superbox.apartment_id==apartment_id).order_by(SBDB_ORM.Superbox.id).first()
                 else:
                     superbox_id=int(superbox_id)
                 if model is None:
                     respond.SetErrorCode(BaseCommand.CS_DEVICEMODEL)
                 elif superbox_id is None:
                     respond.SetErrorCode(BaseCommand.CS_NOSUPERBOX)
                 elif session.query(SBDB_ORM.ApartmentDevice).join(SBDB_ORM.Device).filter(and_(SBDB_ORM.Device.uni_code==dev_code,SBDB_ORM.ApartmentDevice.apartment_id==apartment_id)).first() is not None:
                     respond.SetErrorCode(BaseCommand.CS_DEVICEEXIST)
                 else:
                     apartment=SBDB.IncreaseVersions(session, 0,apartment_id)
                     device=SBDB.GetDeviceForcely(session, dev_code, dev_model)
                     if device is None:
                         device=SBDB_ORM.Device()
                         device.device_model_id=model.id
                         device.uni_code=dev_code
                         
                         obj_dev_model=model#SBDB.GetDeviceModelByName(dev_model)
                         for obj_dev_key in obj_dev_model.device_keys:
                             obj_dev_key_code=SBDB_ORM.DeviceKeyCode()
                             obj_dev_key_code.device_key_id=obj_dev_key.id
                             obj_dev_key_code.key_code=hex(string.atoi(dev_code,16)+obj_dev_key.seq)[2:]
                             device.device_key_codes.append(obj_dev_key_code)
                         session.add(device)
 
                     else:
                         apartment_device=SBDB_ORM.ApartmentDevice()
                         apartment_device.apartment_id=apartment_id
                         apartment_device.name=model.device_type.name
                         apartment_device.superbox_id=superbox_id
                         apartment_device.device_id=device.id
                         
                         for obj_dev_key in device.device_key_codes:
                             obj_apartment_device_key=SBDB_ORM.ApartmentDeviceKey()
                             obj_apartment_device_key.apartment_device_id=apartment_device.id
                             obj_apartment_device_key.device_key_code_id=obj_dev_key.id
                             obj_apartment_device_key.name=model.device_type.name
                             if dev_keys is not None:
                                 for dev_key in dev_keys:
                                     if dev_key[BaseCommand.PN_DEVSEQ]==obj_dev_key.device_key.seq:
                                         obj_apartment_device_key.name=dev_key[BaseCommand.PN_NAME]
                                         break
                             apartment_device.apartment_device_keys.append(obj_apartment_device_key)
                         respond.body[BaseCommand.PN_VERSION]=apartment.version
                         session.add(apartment_device)
                         session.commit()
                         respond.body[BaseCommand.PN_DEVICEID]=device.id
                         #SBDB.setDeviceCodes.update((dev_code,))
             except SQLAlchemyError,e:
                 respond.SetErrorCode(BaseCommand.CS_DBEXCEPTION)
                 logging.error("transport %d:%s",id(self.protocol.transport),e)
                 session.rollback()
         respond.Send()