Enigma 2 and arduino - python

I'm newest with arduino i want to read informations from arduino and write it to dream Box DM800 enigma 2.
i tried this code and it didn't work
# Module de lecture/ecriture du port série
from serial import *
# Port série ttyACM0
# Vitesse de baud : 9600
# Timeout en lecture : 1 sec
# Timeout en écriture : 1 sec
with Serial(port="/dev/ttyACM0", baudrate=9600, timeout=1, writeTimeout=1) as port_serie:
if port_serie.isOpen():
while True:
ligne = port_serie.read_line()
print ligne
Can someone help me please

Related

pynput presses are not being detected by some programs

I'm trying to create a remote using my phone for a game with sockets and pynput. Although some apps such as Chrome or Notepad detect and display the keys that have been pressed with the controller function of pynput (press and release), other ones (such as vba-m, the program I was interested in) just don't register any input. I've tried running the script with admin priviledges, but nothing has changed.
This is the code I'm using:
import socket,threading
from pynput.keyboard import Key, Controller
PORT=12345
SERVER="192.168.1.160"
ADDR=(SERVER, PORT)
FORMAT="utf-8"
TERMINATED="ADIOS"
server=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
conectados=[]
conectadosaddr=[]
keyboard = Controller()
def start(): #Función que se encarga de iniciar el servidor y escuchar nuevas conexiones
server.listen()
print("Servidor iniciado")
while True:
conn,addr=server.accept()
conectados.append(conn)
conectadosaddr.append(addr)
thread=threading.Thread(target=handle_client, args=(conn, addr))
thread.daemon=True
thread.start()
print(f"Conexiones activas: {len(conectados)}")
def handle_client(conn, addr): #Función que se encarga de manejar las conexiones
print(f"Nueva conexion de {addr}")
connected=True
while connected:
try:
data=conn.recv(1024).decode(FORMAT)
if data:
print(f"Recibido: {data} de {addr}")
if data==TERMINATED:
connected=False
print("Se ha cerrado la conexion pacíficamente de "+str(addr))
elif data in "WASDZX":
keyboard.press(data)
keyboard.release(data)
elif data=="BK":
keyboard.press(Key.backspace)
keyboard.release(Key.backspace)
elif data=="ST":
keyboard.press(Key.enter)
keyboard.release(Key.enter)
except Exception as e:
connected=False
print("ERROR: ",e)
print(f"{addr} se ha desconectado")
conectados.remove(conn)
conectadosaddr.remove(addr)
conn.close()
if __name__ == '__main__':
start()
I managed to fix the issue using a different library, called "pydirectinput". It does the same thing pynput does, but its presses are detected by vba-m and many other videogames

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()

Building a server and client with xmlrpc in 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:"

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)

Categories