-
dialoguer par bus série avec l’Arduino :
import termios
import time
d=open("/dev/ttyACM0")
iflag,oflag,cflag,lflag,ispeed,ospeed,cc=termios.tcgetattr(d)
cc[termios.VMIN]=1
cc[termios.VTIME]=0
cflag=termios.CLOCAL|termios.CREAD|termios.B9600|termios.CS8
termios.tcsetattr(d,termios.TCSANOW,[0,0,cflag,0,ispeed,ospeed,cc])
time.sleep(2)
d.write(b'D\x80')
d.write(b'G\x80')
d.write(b'M')
time.sleep(5)
d.write(b'A')
d.close()
- recevoir des paquets UDP d’une page web :
import socket
UDP_IP="127.0.0.1"
UDP_PORT=5005
sock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
sock.bind((UDP_IP,UDP_PORT))
while True:
data,addr=sock.recvfrom(1024)
print "received message:",data
- envoi UDP par une page web PHP :
<?php
$server_ip='127.0.0.1';
$server_port=5005;
$message='A';
if($socket=socket_create(AF_INET,SOCK_DGRAM,SOL_UDP)){
socket_sendto($socket,$message,strlen($message),0,$server_ip,$server_port);
}
}
?>
- ou utiliser Flask pour une solution intégrée :
import flask
import flask_serial
import termios
SERIAL_PORT='/dev/ttyACM0'
web=flask.Flask(__name__)
web.config['SERIAL_PORT'] = SERIAL_PORT
web.config['SERIAL_BAUDRATE'] = 9600
web.config['SERIAL_BYTESIZE'] = 8
web.config['SERIAL_PARITY'] = 'N'
web.config['SERIAL_STOPBITS'] = 1
it=False
def init_term():
d=open("/dev/ttyACM0")
iflag,oflag,cflag,lflag,ispeed,ospeed,cc=termios.tcgetattr(d)
cc[termios.VMIN]=1
cc[termios.VTIME]=0
cflag=termios.CLOCAL|termios.CREAD|termios.B9600|termios.CS8
termios.tcsetattr(d,termios.TCSANOW,[0,0,cflag,0,ispeed,ospeed,cc])
d.close()
s=flask_serial.Serial(web)
@web.route('/')
def use_serial():
return 'use flask serial!'
@web.route('/send/',methods=['GET','POST'])
def send_mess():
global it
if not it:
init_term()
it=True
if flask.request.method=='POST':
m=flask.request.form.get('message')
else:
m=flask.request.args.get('message')
print(m)
s.on_send(m)
return 'message sent.'
@s.on_message()
def handle_message(msg):
print("message received:", msg)
if __name__ == '__main__':
web.run(host="0.0.0.0",port=int("8000"),debug=True)