Ejemplo n.º 1
0
 def runUserScriptEnv(self, uscript):
     from SocketWrap import SocketWrap
     device = self
     value = str(self.lastValue)
     Device.uscriptsOutputPrint[uscript] = ""
     path = common.config['HubServer']['USCRIPTS_PATH'] + uscript
     Log.i('Device/RunUScript', "Reading Users Script at: " + path)
     try:
         f = open(path, "r")
     except EnvironmentError:
         DB.addAlert('', '', 1005, 'Path: ' + path)
         return
     scriptCont = f.read()
     scriptCont = scriptCont.replace(
         "print(", "Device.logUserPrint('" + uscript + "',")
     scriptCont = scriptCont.replace(
         "print (", "Device.logUserPrint('" + uscript + "',")
     scriptCont = scriptCont.replace(
         "print\t(", "Device.logUserPrint('" + uscript + "',")
     f.close()
     #print(scriptCont)
     try:
         exec(scriptCont, locals(), globals())
         res = Device.uscriptsOutputPrint[uscript]
     except Exception as e:
         exc = str(e)
         Log.e('Device/RunUScript',
               "Executing scripts failed with error " + exc)
         DB.addAlert('', '', 1007,
                     uscript + ":\n" + exc + "\n" + traceback.format_exc())
         res = exc
     Log.i('Device/RunUScript', "Executed: " + res)
     #del Task.uscriptsOutputPrint[uscript]
     return res
Ejemplo n.º 2
0
	def checkVPN():
		res = str(check_output("ifconfig".split(" ") ))
		Log.i("PortalConnect","Checking for VPN res:",res)
		if "ppp" not in res:
			res = os.system("sudo pon main updetach persist")
			print(res)
			if res != 0:	
				Log.e("VPN Setup","Error connecting to VPN server(",res)
Ejemplo n.º 3
0
	def connect():
		connected = False
		while True:
			try:
				if(connected == False):
					Log.i("PortalConnect","Connecting to PORTAL",PortalConnect.IP, 4046)
					PortalConnect.checkVPN()
					server_address = (PortalConnect.IP, 4046 )
					PortalConnect.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
					PortalConnect.sock.connect(server_address)
					PortalConnect.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
					PortalConnect.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 1)
					PortalConnect.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 1)
					PortalConnect.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 5)
					Log.i("PortalConnect","Connected to PORTAL")
					PortalConnect.sock.settimeout(3)
					data = {
						'cmd'		: 'register.renew',
						'locIP' 	: PortalConnect.get_lan_ip(),
						'webVer'	: PortalConnect.config ['PortalConnect']['webVer'],
						'hubVer' 	: PortalConnect.getMaxVer(),
						'id' 		: PortalConnect.config ['PortalConnect']['id'],
						
					}
					#PortalConnect.sock.setblocking(0)
					connected = True
					PortalConnect.sock.sendall(json.dumps({"data":data}).encode())
					PortalConnect.thread()
				#data = PortalConnect.sock.recv(1024)
				#Log.i('PortalConnect', "ReReged: ", data)
				#PortalConnect.sock.sendall(b"")
				
				time.sleep(1)
				#if not data:
					#connected = False
					#break
			except ConnectionError as e:
				Log.e('PortalConnect/Connect',"While E: %s"%e)
				connected = False
				time.sleep(5)
				#break
			except ValueError as e:
				Log.e('PortalConnect/Connect',"While E: %s"%e)
				connected = False
				time.sleep(5)
			except socket.error as e:
				#if(e.errno != 11):
				Log.w('PortalConnect/Connect',"Retrying...\n%s"%e)
				connected = False
				time.sleep(5)
Ejemplo n.º 4
0
    def sqlUpdate(sql):
        dbLink, dbCursor = DB.start()
        try:

            dbCursor.execute(sql)
            dbLink.commit()
        except (AttributeError, MySQLdb.OperationalError):
            dbLink, dbCursor = DB.start()
            dbCursor.execute(sql)
        except MySQLdb.Error as e:
            Log.e('DB', " MySQL.Error: %s" % e)
            dbCursor.close()
            dbLink.close()
        dbCursor.close()
        dbLink.close()

        time.sleep(0.1)  # workaround for MySQL cursor hang
Ejemplo n.º 5
0
	def fromJSONstr(socket,jsonStr):
		try:
			jsonObj = json.loads(jsonStr)
			
			'''if(jsonObj["unid"] != "" and jsonObj["setid"] != ""):
				device = Device.findDeviceById(jsonObj["unid"],jsonObj["setid"])
			else:
				device = None'''
			msg = Msg(cmd = jsonObj["cmd"],unid = jsonObj["unid"],setid = jsonObj["setid"],value = jsonObj["value"])

			if("id" in jsonObj):
				msg.id = jsonObj["id"]
			msg.socket = socket
			return msg
		except json.decoder.JSONDecodeError:
			Log.e("MSG/JSON","Invalid JSON: "+jsonStr)
			return Msg(cmd = -1)
Ejemplo n.º 6
0
    def sqlSelect(sql):
        data = []
        dbLink, dbCursor = DB.start()
        try:

            dbCursor.execute(sql)
            dbLink.commit()
            data = (dbCursor.fetchall())
        except (AttributeError, MySQLdb.OperationalError):
            dbLink, dbCursor = DB.start()
            dbCursor.execute(sql)
            data = (dbCursor.fetchall())
        except MySQLdb.Error as e:
            Log.e('DB', " MySQL.Error: %s" % e)
            dbCursor.close()
            dbLink.close()
        dbCursor.close()
        dbLink.close()
        time.sleep(0.1)  # workaround for MySQL cursor hang
        return data
Ejemplo n.º 7
0
    def getInfoFRDB(self):
        if self.unid != '' and self.setid != '':
            Log.i(
                'Device', "Obtaining data device from DB with id %s %s" %
                (self.unid, self.setid))
            sql = """
		SELECT 	units_run.lastValue,
				units_run.id,
				units_run.lastTime,
				units_run.needSetValue,
				units_run.name,
				units_def.description,
				units_def.units,
				units_def.direction,
				units_def.valueType,
				units_def.timeout
		FROM   `units_run`
			   LEFT OUTER JOIN units_def ON units_def.unid = units_run.unid 
		WHERE  units_run.setid = '%s' AND units_run.unid = '%s'
			""" % (self.setid, self.unid)

            data = DB.sqlSelect(sql)
            #print(sql)
            if len(data) == 0:
                Log.e(
                    'Device', "device with ID %s|%s not FOUND!!" %
                    (self.unid, self.setid))
                ##TODO: register as new one
                DB.addAlert(self.unid, self.setid, 1003)
            else:
                data = data[0]
                self.id = data['id']
                self.lastTime = data['lastTime']
                self.lastValue = data['lastValue']
                self.needSetValue = int(data['needSetValue']) == 1
                self.name = data['name']
                self.desc = data['description']
                self.units = data['units']
                self.valueType = data['valueType']
                self.direction = data['direction']
                self.timeout = data['timeout']
Ejemplo n.º 8
0
	def connect():
		try:
			API.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
			API.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
		except Exception as msg:
			Log.e('API',"Could not create socket. Error Code: "+ str(msg[0])+ " Error: "+ str(msg[1]) )
			DB.registerEvent('','','System','Error starting API server: %i %s' % (msg[0],msg[1] ) )
			sys.exit(0)
		

		HOST = ''
		PORT = int(common.config['HubServer']['PORT'])+1
		Log.i('API',"Socket Created at port "+str(PORT))
		# bind socket
		try:
			API.socket.bind((HOST, PORT))
			Log.i('API',"Socket Bound to port " + str(PORT))
		except Exception as msg:
			Log.e('API',"Bind Failed. Error Code: {} Error: {}".format(str(msg[0]), msg[1]))
			DB.registerEvent('','','System','Error binding socket for API server: %i %s' % (msg[0],msg[1] ) )
			sys.exit()
		API.socket.listen(1)
		threading.Thread(target = API.thread, args=()).start()
Ejemplo n.º 9
0
    def onClientConnected(self, unid, setid):
        if setid == '0000':
            device = self.registerDevice(unid)
        else:
            allId = unid + '' + setid
            #device = Device(unid, setid, self)
            if allId not in SocketWrap.allUnits:
                Log.e('SocketWrap', "Not able to egt device ID")
                return
            device = SocketWrap.allUnits[allId]
            device.mySocketWrap = self
            device.isOnline = True
            self.units[allId] = device
            SocketWrap.onlineUnits[allId] = device
            Log.i(
                'SocketWrap', "Dir: " + device.direction +
                ", nedStVal = %s" % device.needSetValue)
            if 'O' in device.direction and device.needSetValue == True:
                Log.i('SocketWrap', "Sending last missed value")
                device.setValue(device.lastValue)

            DB.registerEvent(unid, setid, 'SocketWrap',
                             'Known device connected.')
        return device
Ejemplo n.º 10
0
	def start():
		PortalConnect.config = common.config
		if('PortalConnect' in PortalConnect.config):
			PortalConnect.IP = PortalConnect.config ['PortalConnect']['GATE-IP']
			#PortalConnect.IP = 'localhost'
			
			PortalConnect.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
			res = str(check_output(["sudo","ls","-l","/etc/ppp/peers/"]))

			if "main" not in res:
				vpnConfig = "pptpsetup --create main --server %s --username %s --password %s --encrypt MPPE --start" % (common.config['PortalConnect']['PUBLIC-IP'],common.config['PortalConnect']['user'],common.config['PortalConnect']['passw'])
				res =  str(check_output(vpnConfig.split(" ")))
				Log.i("VPN Setup","pptpsetup create main:",res)
			else:
				print(os.system("sudo poff -a") )
				
			res = os.system("sudo pon main updetach persist")
			print(res)
			if res != 0:	
				Log.e("VPN Setup","Error connecting to VPN server(",res)
			threading.Thread(target = PortalConnect.connect, args=()).start()
			
		else:
			Log.w('PortalConnect',"Hub server not registed, so working in 'offline' mode. Run 'register.py'")
Ejemplo n.º 11
0
PortalConnect.start()
Log.i("TCPM", "Continue booting of HUB")
Log.i('PortalConnect', "Started in TCPM")
lastWiFiSockId = 32
DB.sqlUpdate("""UPDATE `units_run` SET `alive` = '0'""")
#SocketWrap.messagesWaitingACK = dict()
SocketWrap.onlineUnits = {}
SocketWrap.allUnits = {}
SocketWrap.getAllUnitsFromDB()
Task.start()
try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    DB.registerEvent('', '', 'System', 'Hub TCP server started...')
except Exception as msg:
    Log.e(
        'TCPM', "Could not create socket. Error Code: " + str(msg[0]) +
        "Error: " + msg[1])
    DB.registerEvent('', '', 'System',
                     'Error starting hub TCP server: %i %s' % (msg[0], msg[1]))
    sys.exit(0)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

Log.i('TCPM', "Socket Created")
try:
    s.bind((HOST, PORT))
    Log.i('TCPM', "Socket Bound to port " + str(PORT))
except Exception as msg:
    Log.e('TCPM',
          "Bind Failed. Error Code: {} Error: {}".format(str(msg[0]), msg[1]))
    DB.registerEvent(
        '', '', 'System',
Ejemplo n.º 12
0
    def reciveWorker(self):
        self.tcpConn.settimeout(10)
        try:
            if self.IP == '127.0.0.1' or self.IP == 'localhost':
                self.interface = 0
            else:
                self.interface = 1
            self.tcpConn.setblocking(1)

            self.sendMsg(Msg(cmd="device.heartbeat", socket=self,
                             setid="0001"))
            #self.tcpConn.setblocking(0)
            i = 0
            start = time.clock()
            while True:
                ready = False
                sleep(0.002)
                try:

                    if ((time.clock() - start) > 5.0):
                        self.tcpConn.sendall("\n".encode())
                        start = time.clock()
                    data = self.tcpConn.recv(2048).decode('utf-8')
                    if (len(data) > 3):
                        for line in data.split("\n"):
                            if (line != ""):
                                Log.i('SocketWrap', "Received MSG: " + line)
                                msg = Msg.fromJSONstr(self, line)
                                if (msg.cmd == "ACK" or msg.cmd == "0"):
                                    msg.cmd = "ACK"
                                    Log.i(
                                        'SocketWrap',
                                        "ACK recived. Looking for awating msgs "
                                        + msg.toJSON())
                                    toRemove = []
                                    for i in range(len(self.outgoingMSG)):
                                        if (i > len(self.outgoingMSG)):
                                            break
                                        msgS = self.outgoingMSG[i]
                                        if (msgS.setid == msg.setid
                                                and msgS.unid == msg.unid):
                                            Log.i(
                                                'SocketWrap/ACK',
                                                "Msg for ACK found:" +
                                                msgS.toJSON(), msg)
                                            if (msgS.callback != None):
                                                Log.d('SocketWrap/ACK',
                                                      "Calling callback")
                                                msgS.callback(msg)
                                            if (msgS.socket != None):
                                                msgS.socket.sendAck(
                                                    setid=msgS.setid,
                                                    unid=msgS.unid)
                                            toRemove.append(i)
                                            #break
                                    for i in range(len(toRemove)):
                                        try:
                                            del self.outgoingMSG[i]
                                        except:
                                            pass
                                    Log.i('SocketWrap', "ACK proceed complete")
                                elif (msg.cmd == "device.reg.new"
                                      or msg.cmd == "10"):
                                    msg.cmd = "device.reg.new"
                                    self.registerDevice(msg.unid)
                                    #msg.callback = self.sendMsg
                                    #SocketWrap.outgoingMSG.append(msg)
                                elif (msg.cmd == "device.reg.renew"
                                      or msg.cmd == "device.heartbeat"
                                      or msg.cmd == "12" or msg.cmd == "1"):
                                    Log.i('SocketWrap',
                                          "Got MSG: " + msg.toJSON())
                                    allId = msg.unid + '' + msg.setid
                                    if allId not in SocketWrap.allUnits:
                                        Log.e(
                                            'SocketWrap',
                                            "Not able to find device by ID " +
                                            allId + " . Registering as new")
                                        self.registerDevice(
                                            msg.unid, msg.setid)
                                        continue
                                    msg.device = SocketWrap.allUnits[allId]
                                    device = msg.device
                                    device.mySocketWrap = self
                                    device.setIsOnline(True)
                                    self.units[allId] = device
                                    SocketWrap.onlineUnits[allId] = device
                                    if (msg.cmd == "12"):
                                        msg.cmd = "device.reg.renew"
                                    elif (msg.cmd == "1"):
                                        msg.cmd = "device.heartbeat"
                                    if (msg.socket != None):
                                        msg.socket.sendAck(setid=msg.setid,
                                                           unid=msg.unid)
                                    #else:
                                    self.sendAck(setid=msg.setid,
                                                 unid=msg.unid)
                                    #if(device.isOnline ==False):
                                    Log.i(
                                        'SocketWrap', "Dir: " +
                                        device.direction + ", nedStVal = %s" %
                                        device.needSetValue)

                                    if 'O' in device.direction and device.needSetValue == True:
                                        Log.i('SocketWrap',
                                              "Sending last missed value")
                                        device.needSetValue = False
                                        #self.tcpConn.send(allId+''+device.parseFormatToValue(device.lastValue)+'\r\n')

                                        DB.registerEvent(
                                            device.unid, device.setid,
                                            'SocketWrap',
                                            'device register renew.')
                                        device.setValue(device.lastValue)
                                        msg.callback = self.onNeedSetValueAck
                                        #SocketWrap.outgoingMSG.append(msg)

                                elif (msg.cmd == "device.val.input"
                                      or msg.cmd == "20"):
                                    msg.cmd = "device.val.input"
                                    self.sendAck(setid=msg.setid,
                                                 unid=msg.unid)
                                    self.onValueRecieved(
                                        msg.unid, msg.setid, msg.value)
                                elif (msg.cmd == "device.val.set"
                                      or msg.cmd == "22"):
                                    msg.cmd = "device.val.set"
                                    allId = msg.unid + '' + msg.setid
                                    if allId not in SocketWrap.allUnits:
                                        Log.e('SocketWrap',
                                              "Not able to get device ID")
                                        return
                                    device = SocketWrap.allUnits[allId]
                                    Log.d('DeviceSetVal', "[1]")
                                    device.setValue(msg.value,
                                                    callback=sendMsg)
                                    Log.d('DeviceSetVal', "[2]")
                                    msg.callback = self.sendMsg
                                    #SocketWrap.outgoingMSG.append(msg)
                                    #socketWrap.onValueRecieved(msg.unid,msg.setid,value)
                                    Log.d('DeviceSetVal', "[3]")
                        Log.i('SocketWrap', "MSG proceed complete")
                except ValueError as e:
                    Log.e('SocketWrap/ValueError', "While E " + str(e),
                          traceback.format_exc())
                '''except socket.timeout: 
					#self.tcpConn.setblocking(0)
					try:
						if i == 5:
							i = 0
							self.tcpConn.send("\n")
						i+=1
					except:
						break
					#pass
				except socket.error as e:
					#print("[D] While E ", e)
					try:
						if i == 25:
							i = 0
							#self.tcpConn.send("\n")
							self.tcpConn.send(" ")
						i+=1
					except:
						break
					#pass
				
				except Exception as e:
					exc = str(e)
					Log.e('SocketWrap/ValueError',exc)'''
        #finally:
        except socket.error:
            Log.e('SocketWrap/Thread/1', "Closing socket: %s " % socket.error,
                  traceback.format_exc())
        except Exception as e:
            exc = str(e)
            Log.e('SocketWrap/Thread/2', exc, traceback.format_exc())
        Log.i('SocketWrap', "Closing driver ")

        #self.tcpConn.shutdown(2)
        self.tcpConn.close()
        self.onClientDisConnected()
        Log.i('SocketWrap',
              "Client disConnected: " + self.IP + ":" + self.port)
        if 'socketWrap' in locals():
            del self
Ejemplo n.º 13
0
    def registerDevice(self, unid, setid=''):
        Log.i('SocketWrap', "Registering new device " + unid)
        resInfo = DB.sqlSelect(
            "SELECT units_def.description  FROM `units_def` WHERE unid = '%s'"
            % unid)
        if (setid == ''):
            res = DB.sqlSelect(
                "SELECT units_run.setid  FROM `units_run` WHERE units_run.unid = '%s' ORDER BY `id` DESC LIMIT 1 "
                % unid)
        #print("SELECT `id` FROM `units_run` WHERE `unid` = '%s' ORDER BY `id` DESC LIMIT 1 " % unid)
        nextSetdId = ''

        if len(resInfo) == 0:
            Log.e('SocketWrap', 'Unknown produced device connected')
            DB.addAlert(unid, nextSetdId, 1004)
            return Device(0, 0, self)
        else:
            if (setid != ''):
                nextSetdId = setid
            elif len(res) > 0:
                Log.i('SocketWrap', "Last id: %s" % res[0]['setid'])
                nextSetdId = '{:04x}'.format(int(res[0]['setid'], 16) + 1)
            else:
                nextSetdId = '0001'
            nextSetdId = nextSetdId.upper()
            Log.i('SocketWrap',
                  "Registering new device with id: " + unid + "|" + nextSetdId)

            sql = """
				INSERT INTO `units_run`
				(
				 `unid`,
				 `setid`,
				 `lastvalue`,
				 `lasttime`,
				 `timeAdded`,
				 `interface`,
				 `name`,
				 `alive`
				)
				VALUES
				(
				 '%s',
				 '%s',
				 '',
				 '',
				 '%s',
				 '%s',
				 '%s',
				 '1'
				); 
			""" % (unid, nextSetdId, strftime("%Y.%m.%d %H:%M:%S", localtime()),
            self.interface, resInfo[0]['description'])
            id = DB.sqlInsert(sql)

            msg = Msg(unid=unid,
                      setid=setid,
                      cmd="device.reg.res",
                      value=nextSetdId[:2] + ',' + nextSetdId[2:],
                      socket=self)
            self.outgoingMSG.append(msg)

            device = Device(unid, nextSetdId, self)
            device.id = id
            device.isOnline = True
            allId = unid + '' + nextSetdId
            self.units[allId] = device
            SocketWrap.allUnits[allId] = device
            SocketWrap.onlineUnits[unid + '' + nextSetdId] = device

            DB.registerEvent(unid, nextSetdId, 'SocketWrap',
                             'Registered new device!')
            return device
Ejemplo n.º 14
0
	def stop():
		API.threadRun = False
		Log.e('API/Socket'," Stop")
		API.socket.close()
Ejemplo n.º 15
0
	def client_thread(conn, addr):
		conn.settimeout(7)
		conn.setblocking(1)
		try:
			
			#conn.setblocking(0)
			i =0
			while API.threadRun:
				ready = False
				time.sleep(0.2)
				try:
					data = conn.recv(1024)
					if not data:
						break
					#print(data)
					jsonObj = json.loads(data.decode('utf-8'))
					if ('token' not in jsonObj or jsonObj['token'] != API.token):
						conn.send(json.dumps({"errcode": "2003", "msg": "Wrong API token"}).encode())
						conn.close()
					else:
						payload = jsonObj['data']
						if ('cmd' in payload):
							cmd = payload['cmd']
							if (cmd == 'device.value.set'):
								device = Device.findDeviceById(payload['unitId'],payload['setId'])
								Log.i('API/OnValueACK',"Is device online: %i"%device.isOnline)
								while(API.socketAwaitACK !=None):
									continue
								if (device != None):
									API.socketAwaitACK = conn
									device.setValue(payload['value'].strip(), callback=API.onValueSetACK)
									
								else:
									conn.send(json.dumps({"errcode": "3002", "msg": "No such device", "payload":payload}).encode())
							elif (cmd == 'device.value.schedule'):
								device = Device.findDeviceById(payload['unitId'],payload['setId'])
								Log.i('API/OnValueSchedule',"Is device online: %i"%device.isOnline)
								
								if (device != None):
									value = payload['value'].strip()
									print("'",value,"'")
									date = payload['date']
									unid = device.unid
									setid = device.setid
									scriptStr = f'''
newVal = '{value}'
unit    = Device.findDeviceById('{unid}','{setid}')
smsStr = 'sms,all,*'
if unit != None:
	unit.setValue(newVal)
	smsStr = smsStr + 'Value {value} set ok'
else:
	smsStr = smsStr + 'Error setting value {value}'

modems = Device.findDeviceById('0078','')
if len(modems)>0:
	for key, modem in modems.items():
		modem.setValue(smsStr)
'''
									
									uscript = ''.join(random.choice(string.ascii_uppercase + string.digits) for i in range(5))+".py"
									dir = common.config['HubServer']['USCRIPTS_PATH']+'Temp/'
									path = dir+uscript
									if not os.path.exists(dir):
										os.makedirs(dir)
									outFile = open(path, "w+", encoding="utf-8")
									outFile.write(scriptStr)
									outFile.close()
									DB.sqlInsert(f"""
										INSERT INTO `schedule`
										(
											`type`, 
											`time`, 
											`lastTimeRun`, 
											`nextTimeRun`, 
											`script_name`, 
											`active`
										)
										VALUES
										(
											'1',
											'{date}',
											'',
											'',
											'{uscript}',
											'1'
										); 
									""")
									from Tasker import Task
									Task.getAllTasks()
									conn.send(json.dumps({"errcode": "0", "data": {}}).encode())
								else:
									conn.send(json.dumps({"errcode": "3002", "msg": "No such device", "payload":payload}).encode())
							elif (cmd == 'device.conf.set'):
								device = Device.findDeviceById(payload['unitId'],payload['setId'])
								Log.i('API/OnValueACK',"Is device online: %i"%device.isOnline)
								while(API.socketAwaitACK !=None):
									continue
								if (device != None):
									if(device.isOnline):
										API.socketAwaitACK = conn
										device.setSettings(payload['value'], callback=API.onValueSetACK)
									else:
										conn.send(json.dumps({"errcode": "3003", "msg": "Device offline", "payload":payload}).encode())
									
								else:
									conn.send(json.dumps({"errcode": "3002", "msg": "No such device", "payload":payload}).encode())
							elif (cmd == 'device.reg.notif'):
								unid = payload['unitId']
								setid = payload['setId']
								devices = Device.findDeviceById(unid)
								msg = Msg(unid = unid, setid = setid, cmd="device.reg.notif")
								while(API.socketAwaitACK !=None):
									continue
								isNeedAll = True
								Log.d("API/NotifyNew",devices)
								for key, device in devices.items():
									if(device.mySocketWrap != None):
										API.socketAwaitACK = conn
										device.mySocketWrap.sendMsg(msg)
										isNeedAll = False
										break

								Log.d("API/NotifyNew","[4]Point")
								if isNeedAll:
									for socketWrap in SocketWrap.allSockets:
										socketWrap.sendMsg(msg)
									#print("Disc/Is device online",SocketWrap.allUnits["00B40172"].isOnline)
								conn.send(json.dumps({"errcode": "0", "data": {}}).encode())
							elif ('wifi.update' in cmd):
								interface = 'wlan0'
								name = payload['ssid']
								password = payload['password']
								os.system('iwconfig ' + interface + ' essid ' + name + ' key ' + password)
								conn.send(json.dumps({"errcode": "0", "data": {}}).encode())
							elif ('config.update' in cmd):
								if ('db' in cmd):
									common.config.set('DataBase', 'HOST', payload['host'])
									common.config.set('DataBase', 'USER', payload['login'])
									common.config.set('DataBase', 'PASSW', payload['password'])
									common.config.set('DataBase', 'DB', payload['dbname'])
									common.config.set('DataBase', 'CHARSET', payload['charset'])
									DB.close()
									DB.start()
									Log.i('API/ConfigUpdate/DB',"MySQL reconnect")
									conn.send(json.dumps({"errcode": "0", "data": {}}).encode())
							elif ('schedule.update' in cmd):
								from Tasker import Task
								Task.getAllTasks()
								conn.send(json.dumps({"errcode": "0", "data": {}}).encode())
							elif ('uscript.run' in cmd):
								from Tasker import Task
								res = Task.runUserScriptEnv(payload['uscript'])
								conn.send(json.dumps({"errcode": "0", "data": res}).encode())
							elif (cmd == 'system.stat.get'):
								response = {}
								response['Hub_version'] = common.config['HubServer']['VERSION']
								if ('PortalConnect' in common.config):
									response['Hub_id'] = common.config['PortalConnect']['id']
								response['CPU_load'] = str(psutil.cpu_percent()) + '%'
								memory = psutil.virtual_memory()
								# Divide from Bytes -> KB -> MB
								available = round(memory.available/1024.0/1024.0,1)
								total = round(memory.total/1024.0/1024.0,1)
								response['Memory'] = str(available) + 'MB free / ' + str(total) + 'MB total ( ' + str(memory.percent) + '% )'
								
								disk = psutil.disk_usage('/')
								disk_total = round(disk.total / 2**30,2)     # GiB.
								disk_used = round(disk.used / 2**30,2)
								disk_free = round(disk.free / 2**30,2)
								disk_percent_used = disk.percent
								response['Disk'] = str(disk_free) + 'GB free / ' + str(disk_total) + 'GB total ( ' + str(disk_percent_used) + '% )'
								
								conn.send(json.dumps({"errcode": "0", "data": response}).encode())
							elif (cmd == 'system.cmd'):
								shell = payload['shell']
								Log.i('API',"Executing shell cmd %s"%shell)
								#res = str(check_output(shell.split(" ") ))
								res = subprocess.Popen(shell, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=10,shell=True, cwd=os.path.dirname(os.path.realpath(__file__))+"/../" )
								stdout,stderr = res.communicate()
								Log.i('API/',"Executing shell cmd res %s"%stdout)
								res = stdout.decode('utf-8')
								resLo = res.lower()
								if ("error" in resLo or "not exists" in resLo or "forbidden" in resLo or "not allow" in resLo or "failed" in resLo): 
									conn.send(json.dumps({"errcode": "2006", "msg": res}).encode())
								else:
									conn.send(json.dumps({"errcode": "0", "data": res}).encode())
							else:
								conn.send(json.dumps({"errcode": "2005", "data": {'cmd':cmd}}).encode())
				except socket.timeout: 
					try:
						if i == 5:
							i = 0
							conn.send("\n")
						i+=1
					except:
						break
				except socket.error as e:
					try:
						if i == 25:
							i = 0
							conn.send(" ")
						i+=1
					except:
						break
				except ValueError as e:
					Log.e('API/ValueError',"While E: %s"%e)
				except:
					conn.send(json.dumps({"errcode": "2003", "msg": "Error proceeding request"}).encode())
					Log.e('API/ValueError',"During API request execution fail")
		except socket.error as e:
			Log.e('API/ValueError'," Closing driver: %s"% e)
		except ValueError as e:
			Log.e('API/ValueError'," Closing driver: %s"% e)
		conn.close()
		Log.i('API/',"API client disconnected: " + addr[0] + ":" + str(addr[1]))
Ejemplo n.º 16
0
	def thread():
		try:
			conn = PortalConnect.sock
			start = time.clock()
			Log.i('PortalConnect/Thread','Connected')
			i =0
			while True:
				time.sleep(0.002)
				try:
					ready_to_read, ready_to_write, in_error = select.select([conn,], [conn,], [], 5)
				except select.error:
					conn.shutdown(2)    # 0 = done receiving, 1 = done sending, 2 = both
					# connection error event here, maybe reconnect
					
					break
				
				#Log.d('PortalConnect/Time',(time.clock() - start))
				if ((time.clock() - start) > 5.0):
					#Log.d('PortalConnect/Thread','Keep Alvie sent')
					conn.sendall("".encode())
					start = time.clock()
				#try:
				#if len(ready_to_read) > 0:
				data = PortalConnect.sock.recv(len(ready_to_read))
				#if not data:
				#	break
				data = data.decode('utf-8')
				if(data != ""):
					for line in data.split("\n"):
						if len(line)>2:
							Log.i('PortalConnect/Thread','received "%s"' % line)
								
				#time.sleep(0.3)
				#else:
					#break
				'''except socket.timeout: 
					#self.tcpConn.setblocking(0)
					try:
						if i == 5:
							i = 0
							PortalConnect.sock.send("\n".encode())
							time.sleep(0.1)
						i+=1
					except Exception as e:
						Log.e('PortalConnect/ValueError',e)
						break#pass
				except ValueError as e:
					pass
				except socket.error as e:
					#print("[D] While E ", e)
					try:
						if i == 5:
							i = 0
							#self.tcpConn.send("\n")
							PortalConnect.sock.send(" ".encode())
							time.sleep(0.1)
						i+=1
					except Exception as e:
						Log.e('PortalConnect/ValueError',e)
						break
					#pass
				except Exception as e:
					if('Broken pipe'in str(e).lower()):
						Log.e('PortalConnect/Thread',"While E:",e)
						break'''
		except socket.error:
			Log.e('PortalConnect/Thread/1',"Closing socket: %s "% socket.error,traceback.format_exc())
		except Exception as e:
			exc = str(e)
			Log.e('PortalConnect/Thread/2',' %s \n %s' % (exc,traceback.format_exc()))
		Log.e('PortalConnect/Thread/3',"Closing socket")
		#except ValueError:
			#print ('closing socket', ValueError)
		PortalConnect.sock.shutdown(2)
		PortalConnect.sock.close()
		PortalConnect.connect()
Ejemplo n.º 17
0
 def doFormat(self):
     Log.e(TAG, "No implementation of ZipFormatter.doFormat() if found.")
     raise Exception("Should be implemented by sub-class!")
Ejemplo n.º 18
0
 def doFormat(self):
     Log.e(TAG, "No implementation of ZipFormatter.doFormat() if found.")
     raise Exception("Should be implemented by sub-class!")