def message_receive_LV(sock): assert(sock is not None) length = len(struct.pack("@I", 0)) try: buff = sock.recv(length) except Exception: log.error("Error in receiving message form socket...") message = '' if len(buff) == 0: return message message_length = int(struct.unpack("@I", buff)[0]) log.debug("message_length = '%d'" % message_length) if message_length < 0: raise RuntimeError("Got wrong message (length = %d" % message_length) if message_length == 0: log.debug("Message length is 0, skipping body") return message log.debug("Receiving V") while len(message) < message_length: chunk = sock.recv(message_length - len(message)) log.debug("Got a chunk (%d byte(s))" % len(chunk)) if chunk == '': raise RuntimeError("Broken connection") message = message + chunk log.debug("Message received (%d byte(s))" % len(message)) return message
def __socket_set(self, value): if self.___socket != value: m = "Socket '%s' has been " % self.__name if value is None: m = m + "destroyed" else: m = m + "created" log.debug(m) self.___socket = value
def capturarDatos(self): GPIO.setmode(GPIO.BCM) GPIO.setup(self.GPIO_PIN, GPIO.IN) valor = GPIO.input(self.GPIO_PIN) estado = "Oscuridad" if(valor <= 0.5) : estado = "Luz" log.debug( '%s (%d)'%(estado, valor)) self.guardarDatos(valor)
def __create(self): if self.__socket is None: log.debug("Socket '%s' is not available" % self.__name) self.__connected = False self.__socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) assert(self.__socket is not None) self.__socket.settimeout(None) else: log.debug("Socket '%s' already created" % self.__name)
def capturarDatos(self): arduino = serial.Serial('/dev/ttyUSB0', 9600) arduino.write("0YL69") time.sleep(2) #Esto lee todas la lineas msg = arduino.read(arduino.inWaiting()) log.info(msg) objs = json.loads(msg) #humedad = -1 * (obj["ao"] / 1023) * 100 + 100 for obj in objs: humedad = -1 * (float(obj["ao"]) / float(1023)) * 100 + 100 sensor = "%d, %d" % (obj["dpin"], obj["apin"]) humedadStr = "Humedad Tierra={0:0.1f}%".format(humedad) log.debug("%s en sensor %s" % (humedadStr, sensor)) self.guardarDatos(obj, humedad)
def run(query=''): log.debug("%s"%query) conn = MySQLdb.connect(*config.datosDB) # Conectar a la base de datos cursor = conn.cursor() # Crear un cursor cursor.execute(query) # Ejecutar una consulta if query.upper().startswith('SELECT'): data = cursor.fetchall() # Traer los resultados de un select else: conn.commit() # Hacer efectiva la escritura de datos data = None cursor.close() # Cerrar el cursor conn.close() # Cerrar la conexion return data
def run(query=''): log.debug("%s" % query) conn = MySQLdb.connect(*config.datosDB) # Conectar a la base de datos cursor = conn.cursor() # Crear un cursor cursor.execute(query) # Ejecutar una consulta if query.upper().startswith('SELECT'): data = cursor.fetchall() # Traer los resultados de un select else: conn.commit() # Hacer efectiva la escritura de datos data = None cursor.close() # Cerrar el cursor conn.close() # Cerrar la conexion return data
def __init__(self, name, host, port, timeout): assert(name is not None) assert(host is not None) assert(port is not None) log.debug("Socket client initializing '%s' (%s, %s, %s)" % (name, host, port, timeout)) self.__name = name self.__host = host self.__port = int(port) self.__timeout = int(timeout) self.___socket = None self.__connected = False self.__socket = None self.__create()
def __init__(self, name, retry_time, listen_backlog, bind_addr, bind_port, handlers_factory): self.__name = name self.__retry_time = int(retry_time) self.__listen_backlog = int(listen_backlog) self.__bind_addr = bind_addr self.__bind_port = int(bind_port) self.__handlers_factory = handlers_factory assert(self.__name is not None) assert(self.__handlers_factory is not None) assert(self.__retry_time >= 1) assert(self.__listen_backlog >= 0) assert(self.__bind_port >= 0) log.debug("Socket server '%s' initializing ..." % self.__name) self.__server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) assert(self.__server_sock is not None) self.__server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) log.debug("Socket server '%s' binding to %s:%d" % (self.__name, self.__bind_addr, self.__bind_port)) self.__server_sock.bind((self.__bind_addr, self.__bind_port)) super(Server, self).__init__() super(Server, self).setDaemon(True) super(Server, self).start()
def connect(self): if self.__socket is None: self.__create() if self.__connected: log.debug("Socket already connected") return log.debug("Socket '%s' connecting to %s:%d)" % (self.__name, self.__host, self.__port)) self.__socket.connect((self.__host, self.__port)) log.debug("Socket '%s' is now connected" % self.__name) self.__connected = True
def __sleep(self, timeout): log.debug("Socket '%s' sleeping for %d second(s)" % (self.__name, timeout)) time.sleep(timeout)
def message_send(sock, message): assert(sock is not None) assert(message is not None) log.debug("Sending message '%s'" % message) message_send_LV(sock, message)
def message_send_LV(sock, message): log.debug("Sending LV message '%s'" % str(message)) totalsent = 0 message_length = len(message) log.debug("Sending header") tempsent = 0 buff = struct.pack("@I", message_length) while tempsent < len(buff): sent = sock.send(buff[tempsent:]) log.debug("%d byte(s) sent" % sent) if sent < 0: raise RuntimeError("Broken connection") tempsent = tempsent + sent totalsent = totalsent + tempsent if message_length == 0: log.debug("Message length is 0, skipping body") return log.debug("Sending body '%s'" % str(message)) tempsent = 0 buff = message while tempsent < len(buff): sent = sock.send(buff[tempsent:]) log.debug("%d byte(s) sent" % sent) if sent < 0: raise RuntimeError("Broken connection") tempsent = tempsent + sent totalsent = totalsent + tempsent log.debug("Message sent (%d byte(s))" % totalsent)
def run(self): handlers = [] while True: log.debug("Running body for socket server '%s'" % self.__name) #try: self.__server_sock.listen(self.__listen_backlog) while True: log.debug("Socket server '%s' is waiting for connection" % self.__name) (sock, addr) = self.__server_sock.accept() client_address = addr[0] client_port = int(addr[1]) endpoint = "%s:%d" % (client_address, client_port) log.debug("Socket server got connection from '%s'" % endpoint) name = self.__name + "-" + endpoint log.debug("Creating handler '%s'" % name) handlers.append(self.__handlers_factory.create(name, sock)) log.debug("Handler '%s' created" % name) log.debug("Socket server '%s' execution completed" % self.__name)