简体   繁体   English

树莓派python服务器未发送串行读/写命令

[英]Raspberry pi python server not sending serial read/write commands

I've got two servers (written in python) that are nearly identical in the way they handle serial communications on the Pi. 我有两台服务器(用python编写),它们在Pi上处理串行通信的方式几乎相同。 However, one works and the other one doesn't and I can't seem to find the problem. 但是,一个有效,而另一个无效,我似乎找不到问题。 I've hooked up a logic analyzer and the first server triggers the rx/tx properly when communicating serially, however, the second server will not trigger anything. 我已经连接了逻辑分析仪,当串行通信时,第一台服务器会正​​确触发rx / tx,但是,第二台服务器将不会触发任何操作。

First (working) server - cut down to show only the serial: 第一台(正在运行的)服务器-缩减为仅显示序列号:

import socket
import sys
import RPi.GPIO as GPIO
from serial import Serial

#HOST = ' ' # Symbolic name meaning all available interfaces
PORT = 8888 # Arbitrary non-privleged port
ser = 0

#accepts a command as a string, parameters separated by white space
def processData( data ):
    print ( "cmd : " + data).strip()
    parseData = data.split(" ")
    cmdLength = len(parseData)
    cmd = parseData[0]

    if cmd == "digitalWritePin":
        pin = parseData[1]
        state = parseData[2]
        #GPIO.setup(pin, GPIO.OUT) # SHOULD HAVE ALREADY BEEN DONE W/ A CONFIG!!!
        if state == '1':
            GPIO.output(int(pin), True)
        elif state == "0":
            GPIO.output(int(pin), False)
    elif cmd == "serialConfig":
        baudRate = int(parseData[1])
        timeOut = int(parseData[2])
        global ser
        ser = Serial('/dev/ttyAMA0', baudRate, timeout=timeOut)
    elif cmd == "serialWrite":
        serialcmd = parseData[1]
        writeBuff = data.split("serialWrite")
        #print writeBuff[1].strip(" ")
        ser.write(writeBuff[1].strip(" "))
    elif cmd == "serialReadLine":
        print "serial read:"
        response = ser.readline()
        print response
        conn.sendall(response)
        print "read done"

    return

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
s.bind((HOST,PORT))
print 'Socket bind complete'

s.listen(10)    #parameter: backlog, controls number of connections that are 'queued'
print 'Socket now listening'

#Function f or handling connections. this will be used to create threads
def clientthread(conn):
    #sending message to connected client        
    try:
        while True:
            data = conn.recv(1024)
            if not data:
                break
            processData( data )

        #out of the loop
        conn.close()
    except socket.error , msg:
        print 'Recv failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]

while 1:
    #wait to accept a connection - blocking call
    conn, addr = s.accept()
    print 'Connected with ' + addr[0] + ':' + str(addr[1])

    #start new thread takes 1st argument as a function name to be run
    #second is the tuple of arguments to the function
    start_new_thread(clientthread,(conn,))

s.close

the most important parts of that being: 其中最重要的部分是:

    ser = Serial('/dev/ttyAMA0', baudRate, timeout=timeOut)

and the serial config/read/write areas of the el/if block 以及el / if块的串行配置/读/写区域

and the second sever (that is not working): 和第二个服务器(不起作用):

import socket
import sys
from time import sleep
from serial import Serial
from thread import *
import binascii

#HOST = ' ' # Symbolic name meaning all available interfaces
HOST = '10.1.10.28'
PORT = 8889 # Arbitrary non-privleged port


s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'

try:
    s.bind((HOST,PORT))
except socket.error , msg:
    print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
    sys.exit()

print 'Socket bind complete'

s.listen(10)    #parameter: backlog, controls number of connections that are 'queued'
print 'Socket now listening'

ser = Serial('/dev/ttyAMA0', baudrate = 115200, timeout= 10)
#ser.open #--- uncommenting this does not make a difference 

#Function f or handling connections. this will be used to create threads
def clientthread(conn):

    #infinite loop so the function does not terminate and thread does not end
    try:
        while True:
            print  "step 1"
            first = conn.recv(1)
            print  "step 2"
            if not first:
                break
            hextFirst = hex( ord(first) )
            print hextFirst
            if hextFirst == '0xff':
                print  "step 3"
                #ser.write(hextFirst)           #send 0xff (converted)
                ser.write(first)                #send 0xff (orignal)

                length = conn.recv(1)               #get length
                hextLength = hex( ord(length) )     #convert length
                intlength = ord(length)
                print "hextLength: " + hextLength
                print "step 4"
                #ser.write(hextLength)          #send length (converted)
                ser.write(length)               #send length (original)
                cmd = 0
                if ord(length) == 0:
                    cmd = conn.recv(13)
                else:
                    cmd = conn.recv(ord(length)-2)

                hextCmd = binascii.b2a_hex(cmd)

                print cmd
                print "hextCmd: " + hextCmd
                #ser.write(hextCmd)         #send cmd (converted)
                ser.write(cmd)              #send cmd (original)

                #sleep(1)
                response = ser.read(1)          #get response
                #hextResponse = hex(ord(response))

                print "serial resp: " + response
                conn.sendall(response)          #send response to LV
                print "step 5"
            print "step 6"
            sleep(10)

        #out of the loop
        conn.close()
    except socket.error , msg:
        print 'Recv failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]

try:
    while 1:
        #wait to accept a connection - blocking call
        conn, addr = s.accept()
        print 'Connected with ' + addr[0] + ':' + str(addr[1])

        #start new thread takes 1st argument as a function name to be run
        #second is the tuple of arguments to the function
        start_new_thread(clientthread,(conn,))

    s.close
except KeyboardInterrupt:
    ser.close
    s.close
    print "Exiting: Keyboard Interrupt"

I realize that is alot of code to go through, but you can ignore most of it, i'm just wondering what went wrong in the serial config/write. 我意识到这是很多代码,但是您可以忽略其中的大部分,我只是想知道串行配置/写入中出了什么问题。 Like i said initially, the problem comes from the logic analyzer not seeing any serial communications (to or from) on the 2nd server, while the first server is working just fine 就像我最初说的那样,问题出在第二台服务器正常工作时,逻辑分析仪在第二台服务器上看不到任何串行通信(往返)

Try releasing /dev/ttyAMA0 from the default console by editing /boot/cmdline.txt 尝试通过编辑/boot/cmdline.txt从默认控制台释放/ dev / /boot/cmdline.txt

dwc_otg.lpm_enable=0 console=ttyAMA0,115200 kgdboc=ttyAMA0,115200 console=tty1 ..

change it to 更改为

dwc_otg.lpm_enable=0 console=tty1 .....

and removing this line from /etc/inittab 并从/ etc / inittab中删除此行

T0:23:respawn:/sbin/getty -L ttyAMA0 115200 vt100

also make sure you run the program as super user sudo 还请确保您以超级用户sudo身份运行该程序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM