Building a server and client with xmlrpc in python - python

I'm trying to build a client and a server using xmlrpc in python, I HAVE to use a class named FunctionWrapper which has a method and the client use it, the method's name is sendMessage_wrapper(self, message), and the server is declared in another class, I'm trying to register the method in the server but when i call the method from de client I raise and error, can you help me, please?
Cliente:
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import xmlrpclib
from SimpleXMLRPCServer import SimpleXMLRPCServer
from os import path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
from Constants.Constants import *
class MyApiClient:
def __init__(self, contact_port = DEFAULT_PORT,contact_ip=LOCALHOST_CLIENT):
self.contact_port = contact_port
self.contact_ip = contact_ip
self.proxy = xmlrpclib.ServerProxy(contact_ip+str(self.contact_port)+"/")
def sendMessage(self,message):
self.proxy.sendMessage_wrapper(message)
a = MyApiClient()
a.sendMessage("Hi")
a.sendMessage("WORKING")
Server:
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import xmlrpclib
from SimpleXMLRPCServer import SimpleXMLRPCServer
from os import path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
from Constants.Constants import *
class MyApiServer:
def __init__(self,wrapper, my_port = DEFAULT_PORT):
self.port = my_port
self.server = SimpleXMLRPCServer((LOCALHOST,self.port))
self.wrapper = wrapper
self.server.register_instance(self.wrapper)
print("Running")
self.server.serve_forever()
class FunctionWrapper:
def __init__(self):
self.message = None
"""
Procedimiento que ofrece nuestro servidor, este metodo sera llamado
por el cliente con el que estamos hablando, debe de
hacer lo necesario para mostrar el texto en nuestra pantalla.
"""
def sendMessage_wrapper(self, message):
self.message = message
self.showMessage()
def showMessage(self):
print ("Mensaje "+self.message)
#raise NotImplementedError( "Should have implemented this" )
a = FunctionWrapper()
b = MyApiServer(a)

Here are the constants in case you need it
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#Nombres para etiquetas login local y remoto
MY_PORT_NUMBER_TITLE = "Cual es mi puerto?"
OTHER_PORT_NUMBER_TITLE = "Cual es el puerto de contacto?"
OTHER_IP_NUMBER_TITLE = "Cual es la direccion ip de contacto?"
LOGIN_TITLE = "Acceder"
#Nombres para las etiquetas del chat
CONVERSATION_TITLE = "Conversacion"
SEND_TITLE = "Responder"
#Titulo de las ventans GUI
LOGIN_WINDOW = "Login"
CHAT_WINDOW = "Chat"
#Modos de acceso al chat, local o remoto
LOCAL = "Local"
REMOTE = "Remote"
#Mensajes de error
WARNING = "¡Alerta!"
MISSING_MESSAGE = "No hay ningun mensaje para enviar"
#Localhost
LOCALHOST = "localhost"
DEFAULT_PORT = 5000
LOCALHOST_CLIENT = "http://localhost:"

Related

Send a def with sockets in python

I have a problem with sockets, I wanna sent the especifications about my pc in a chat created with sockets, but when I use the sentence send() with the function the compiler throw this error... How can I send that information? Thanks. This is the server code.
#importar librerias
import psutil
import platform
from datetime import datetime
from socket import *
uname = platform.uname()
direccionServidor = "localhost"
puertoServidor = 9099
#Generar un nuevo socket
socketServidor = socket (AF_INET, SOCK_STREAM)
#Se establece conexion
socketServidor.bind((direccionServidor, puertoServidor))
socketServidor.listen()
def informacion():
print("="*40, "System Information", "="*40)
print(f"System: {uname.system}")
print(f"Node Name: {uname.node}")
print(f"Release: {uname.release}")
print(f"Version: {uname.version}")
print(f"Machine: {uname.machine}")
print(f"Processor: {uname.processor}")
while True:
# se establece conexion
socketConexion, addr = socketServidor.accept()
print("Conectado con cliente",addr)
while True:
#recibe el mensaje del cliente
mensajeRecibido = socketConexion.recv(4096).decode()
print(mensajeRecibido)
if mensajeRecibido == 'informacion':
socketConexion.send(informacion())
#condicion de salida
if mensajeRecibido == 'exit':
break
socketConexion.send(input().encode())
print("Desconectado del cliente",addr)
#cerramos conexion
socketConexion.close()
The error:
line 39, in <module>
socketConexion.send(informacion())
TypeError: a bytes-like object is required, not 'NoneType'
Like this:
def informacion():
msg = ["="*40, "System Information", "="*40]
msg.append(f"System: {uname.system}")
msg.append(f"Node Name: {uname.node}")
msg.append(f"Release: {uname.release}")
msg.append(f"Version: {uname.version}")
msg.append(f"Machine: {uname.machine}")
msg.append(f"Processor: {uname.processor}")
return '\n'.join(msg)
...
socketConexion.send(information().encode())

Launching Python script including Paho-mqtt library in RPi rc.local

I have installed Paho-mqtt python libray by "pip3 install paho-mqtt" on my RPi which I use for home automation purposes.
I made a python script to regulate my heatpump.
My script:
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Programme de régulation de température
"""
import time
import json
import requests
from requests.auth import HTTPBasicAuth
import paho.mqtt.subscribe as subscribe
import paho.mqtt.publish as publish
#***********Récupération de l'état d'un élément de Domoticz***********
def dom_elmt(idx, valeur):
url= 'http://127.0.0.1/json.htm?type=devices&rid='
adresse= url+idx
r=requests.get(adresse)
status=r.status_code
if status == 200:
# l'API renvoie 200 si tout est OK
getinfos=r.json()
for i, v in enumerate(getinfos["result"]):
#Récupération de la donnée "Status" du switch
result= getinfos["result"][i][valeur]
return result
#***********FIN Récupération de l'état du clavier************
#***********
Prev_Setpoint = 0
while True:
msg = subscribe.simple("zigbee2mqtt/Thermo-Hygro Salle", hostname="127.0.0.1")
y = json.loads(msg.payload)
Temp = y["temperature"]
print(time.strftime('%H:%M:%S', time.localtime()) ,"Température salle : ",Temp)
#******** lecture du point de consigne idx: 230 ************
Consigne=dom_elmt('230', "SetPoint")
Consigne=float(Consigne)
if Temp > Consigne + 0.2:
Setpoint = Consigne - 0.5
if Temp >= Consigne - 0.2 and Temp <= Consigne + 0.2:
Setpoint = Consigne
if Temp < Consigne - 0.2:
Setpoint = Consigne + 0.5
Setpoint = str(Setpoint) # Transformation d'un float en str
if Setpoint != Prev_Setpoint: # Le point de consigne calculé est différent du précédent
a = "{"
b = '"temperature"'
c = ":"
d = "}"
sendtemp = a+b+c+Setpoint+d
publish.single("heatpump/set", sendtemp, hostname="127.0.0.1")
Prev_Setpoint = Setpoint # Mise à jour de Prev_Setpoint
If I launch this script on a console it works perfectly. I need but I can't launch it at boot in the rc.local.
....
if [ "$_IP" ]; then
printf "My IP address is %s\n" "$_IP"
fi
python /home/pi/thermostat.py &
exit 0
This don't work and I don't understand what happen ?! (I launched other scripts in rc.local whithout any problem)
Does someone has an idea to help me ???
Thanks in advancecd
This is because the python script will get killed when the script that started it exits even if it is pushed to the background with &.
The hacky solution is to prefix the command with nohup (which means the process will not get sent the Hang Up signal when the parent script exits).
The better option would be to write a proper systemd service definition for your script.

problem with send() function using socket in python

I'm using socket in python between 2 laptop to send informations. But I have an error and i can't resolve it. (I'm a debutant in python). The problem is when i trierd to send information with send() function
Traceback (most recent call last):
File "client.py", line 60, in <module>
client.send(GetMyInfo.scan())
TypeError: send() argument 1 must be string or buffer, not None
Maybe the error is due my function Getinfo ?
I'm using a class with functions (listinfo() here).
Thx
Here is the code :
import socket
import subprocess
import os,sys
#==========================================================================================
#creation d'une classe pour rendre le programme oriente objet
class GetInfo:
infos = os.uname()
currentUser = os.getlogin()
rep_actuel = os.getcwd()
myDirectory = os.listdir("/Users/")
def listInfo(self):
#afficher des informations sur le systeme
print "Informations du systeme :{} ".format(GetInfo.infos)
#afficher l'utilisateur actuel
print "Current user : {} \n".format(GetInfo.currentUser)
#afficher le path du repertoire actuel
print "Repertoire actuel : {} \n".format(GetInfo.rep_actuel)
def scan(self):
print "Liste de tous les repertoires dans Users/"
#on liste toutes les directories et sous directories
for file in GetInfo.myDirectory:
print file
#instance de l objet GetInfo (creation de l'objet)
GetMyInfo = GetInfo()
# afficage des infos de l'objet
#GetMyInfo.listInfo()
#GetMyInfo.scan()
#==========================================================================================
# on cree un objet socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print "Socket successfully created"
# reservation d'un port specifique
port = 12345
# contient le nom d hote et le numero du port
#identifiant le serveur auquel on veut se connecter.
s.bind(('127.0.0.1', port))
print "socket binded to %s" %(port)
# activation du mode ecoute
# avec un nombre maximum de connexions qu il peut recevoir sur ce port sans les accepter
s.listen(5)
print "socket is listening"
#==========================================================================================
# gestion des erreurs
while True:
# on etabli la connection avec le client
client, addr = s.accept()
print 'Got connection from', addr
# send the informations about the victim.
client.send(GetMyInfo.scan())
print client.recvfrom(2048)
# on ferme la connection
s.close()

Using asyncio to read the output of a serial port

I have been doing some port-reading for work, and I need to know if I should use asyncIO to read the data that comes in from this port.
Here's some details about the way in which the system is constructed.
Multiple sensors are being read at the same time and might produce output that goes in at the same time. (all data comes in through a probee ZU10 connected to a usb port) All data must be timestamped as soon as it comes in.
The data is supposed to be processed and then sent to a django webapp through a REST API.
The thing Is, it's really important not to lose any data, I'm asking about this because I believe there must be an easier way to do this than the one I'm thinking of.
The way I want the data to come in is through an asyncronous process that takes in the data into a queue and timestamps it, this way there is no way in which loss of data is present, and timestamping may be no more than a few fractions of a second off, which is not a problem.
If anyone has got any ideas I would be thankful for them
Here's the code I'm using to open the port, take the data in and what I've got so far on the actually reading the meaningful data.
Here's the reading part:
import serial #for port opening
import sys #for exceptions
#
#configure the serial connections (the parameters differs on the device you are connecting to)
class Serializer:
def __init__(self, port, baudrate=9600, timeout=.1):
self.port = serial.Serial(port = port, baudrate=baudrate,
timeout=timeout, writeTimeout=timeout)
def open(self):
''' Abre Puerto Serial'''
self.port.open()
def close(self):
''' Cierra Puerto Serial'''
self.port.close()
def send(self, msg):
''' envía mensaje a dispositivo serial'''
self.port.write(msg)
def recv(self):
''' lee salidas del dispositivo serial '''
return self.port.readline()
PORT = '/dev/ttyUSB0' #Esto puede necesitar cambiarse
# test main class made for testing
def main():
test_port = Serializer(port = PORT)
while True:
print(test_port.recv())
if __name__ == "__main__":
main()
And a bit of what I'm going to be using to filter out the meaningful reads (bear with it, it might be full of awful errors and maybe a terrible RegEx):
import re
from Lector import ChecaPuertos
from Lector import entrada
patterns = [r'^{5}[0-9],2[0-9a-fA-F] $'] #pattern list
class IterPat:
def __init__(self, lect, pat = patterns):
self.pat = pat # lista de patrones posibles para sensores
self.lect = lect # lectura siendo analizada
self.patLen = len(pat) #Largo de patrones
def __iter__(self):
self.iteracion = 0 #crea la variable a iterar.
def __next__(self):
'''
Primero revisa si ya pasamos por todas las iteraciones posibles
luego revisa si la iteración es la que pensabamos, de ser así regresa una
tupla con el patrón correspondiente, y la lectura
de otra forma para el valor de ser mostrado
'''
pattern = re.compile(self.pat[self.iteracion])
comp = pattern.match(self.lect)
if comp == True:
re_value = (self.pattern, self.lect)
return re_value
else:
self.iteración += 1
def main():
puerto = ChecaPuertos.serial_ports()
serial = entrada.Serializer(port = puerto[0])
if serial != open:
serial.open()
while True:
iter = IterPat()
#This is incomplete right here.
I am using asyncio to read/write a serial port with pyserial. I am having my device on the other end of the serial connection write a single byte when it is ready to receive a payload. Asyncio watches for that byte then sends the payload. It looks something like this:
serial_f = serial.Serial(port=dev, baudrate=BAUDRATE, timeout=2)
def write_serial():
status = serial_f.read(1)
serial_f.write(buffer)
loop = asyncio.get_event_loop()
loop.add_reader(serial_f.fileno(), write_serial)

how to install pythonwebkit and pywebkitgtk in ubuntu?

i am a new to use ubuntu.
i want to install pythonwebkit and pywebkitgtk in ubuntu,but i have tryed a long time. even thongth i can install,but,when i excute this code,
#!/usr/bin/env python
import pygtk
pygtk.require("2.0")
import gi
from gi.repository import WebKit as webkit, Gtk as gtk
dir(gtk)
print dir(gtk.WindowType)
init_string="""
<div id="testing">testing</div>
<div><button id="link">CLICK ME</button>
"""
class Browser:
# Ventana del programa
def __init__(self):
self.window = gtk.Window(type=gtk.WindowType.TOPLEVEL)
self.window.set_position(gtk.WindowPosition.CENTER)
self.window.set_default_size(800, 600)
self.window.fullscreen()
self.window.connect("destroy", self.on_quit)
# Un vBox, en la parte de arriba hay una caja para ingresar
# la direccion web, y abago se muestra la pagina
vbox = gtk.VBox()
# La parte en donde se muestra la pagina que se visita (con scroll incluido)
self.scroll_window = gtk.ScrolledWindow()
self.webview = webkit.WebView()
print dir(self.webview)
#self.scroll_window.add(self.webview)
# Unimos todo en el vBox
#vbox.pack_start(self.url_text, True, False, 0)
# El expand=False al empaquetarlo es para que el entry no ocupe media pantalla
#vbox.pack_start(self.scroll_window, True, True, 0)
#self.window.add(vbox)
self.window.add(self.webview)
self.window.show_all()
self.webview.load_string(init_string, "text/html", "utf-8", '#')
doc = self.webview.get_dom_document()
self.webview.connect('document-load-finished', self.onLoad)
print doc
print dir(doc)
def onLoad(self, param1, param2):
print "STARTING"
doc = self.webview.get_dom_document()
div = doc.get_element_by_id('testing')
print div
print dir(div)
print div.get_inner_html()
div.set_inner_html('DYNAMIC TEXT')
link = doc.get_element_by_id('link')
#print link
#print dir(link)
link.connect('click-event', self.onClick, link)
#div.connect_object('click-event', self.onClick, link)
def print_childs(self, elem):
childs = elem.get_child_nodes()
for c in range(childs.get_length()):
i=childs.item(c)
#print dir(i)
print "%s - %s\n" %(i.get_tag_name(), i.get_inner_html())
self.print_childs(i)
def onClick(self, p1, p2, p3=None):
print "CLICKED - %s %s %s " % (str(p1), str(p2), str(p3))
#return False
def on_quit(self, widget):
gtk.main_quit()
if __name__ == "__main__":
browser = Browser()
try:
while True:
gtk.main_iteration()
except:
gtk.quit()
print "BAILING OUT!"
the "doc = self.webview.get_dom_document()" can't pass,the error is webview does not have the get_dom_document attr.
what should i can do? i must access the dom tree, please!
i know the way i install pythonwebkit or pywebkitgtk has something wrong,but i can't do right.
is someone can help?
Run your import directives in the interpreter.
If that doesn't throw any exceptions (as I gather from where you say the error arises), then the problem is most likely not with installing the libraries, and has nothing to do with Ubuntu.
Python is not saying 'hey, this is not installed correctly', it's saying 'hey, you're handling this object incorrectly! The function you want to reach is not there!'.
Recheck the approapiate documentation, and see how to get the DOM tree.
edit -- I got this from a quick google query.
def _view_load_finished_cb(self, view, frame):
doc = frame.get_dom_document()
nodes = doc.getElementsByTagName('body')
body = nodes.item(0)
You're trying to access the DOM tree from an object that doesn't provide it.

Categories