1

在使一个ros和一个基于 python 的 http 服务器工作遇到很多麻烦之后,我还有另一个问题是结合两个不同的代码。

到目前为止,这是我编写的用于编写发布ros主题但同时响应 http 服务器的代码的内容。问题是服务器没问题,除非我更换

httpd.serve_forever()

httpd.service_actions

使其无阻塞。然后服务器没有响应。有什么办法可以解决这个问题,同时保持代码不阻塞?

#!/usr/bin/env python3

import rospy
from std_msgs.msg import String

from http.server import BaseHTTPRequestHandler, HTTPServer

class S(BaseHTTPRequestHandler):
    def _set_headers(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def do_GET(self):
        self._set_headers()
        self.wfile.write(b"<html><body><h1>hi!</h1></body></html>")

    def do_HEAD(self):
        self._set_headers()

    def do_POST(self):
        # Doesn't do anything with posted data
        self._set_headers()
        self.wfile.write(b"<html><body><h1>POST!</h1></body></html>")

def http_server_init(port,server_class=HTTPServer, handler_class=S):
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    print('Starting httpd...')
    return (httpd)

def http_server_loop(httpd):
    #httpd.serve_forever()
    httpd.service_actions()

def talker_init():
    pub = rospy.Publisher('chatter', String, queue_size=10)
    rospy.init_node('talker', anonymous=True)
    rate = rospy.Rate(10) # 10hz
    return (pub,rospy,rate)

def talker_loop(pub,rospy,rate):
        hello_str = "hello world %s" % rospy.get_time()
        rospy.loginfo(hello_str)
        pub.publish(hello_str)
        rate.sleep()

if __name__ == '__main__':
    from sys import argv
    if len(argv) == 2:
        http_port=int(argv[1])
    else:
        http_port=8080
    httpd=http_server_init(http_port)
    try:
        pub,rospy,rate=talker_init()
        while not rospy.is_shutdown():
            http_server_loop(httpd)
            talker_loop(pub,rospy,rate)
    except rospy.ROSInterruptException:
        pass

顺便说一句,在 ROS 中,这段代码应该通过

rosrun <packagename> <script>.py

从 bash 调用会导致错误。除非您删除ROS- 相关代码。

4

0 回答 0