【发布时间】:2014-10-23 18:25:30
【问题描述】:
我正在为我的树莓派开发一个 python 应用程序。这个软件的目的是监听另一个软件的 POST,当我收到 POST 时,我想通过连接到树莓的 zigbee 模块发送消息。
我的问题是我如何在 python 中为树莓派实现网络服务器,我无法访问能够通过 zigbee 发送消息的类。
[更新] 为了更清楚,我的问题是我无法在 do_POST 方法中访问 wsanProtocol。所以我的界面不能用于 xbee。
你能给我一些关于如何做的想法吗?
这是我的网络服务器的代码:
class webServer(threading.Thread):
def __init__(self, serverAddress, port, wsanProtocol):
self.wsanProtocol = wsanProtocol
self.serverAddress = serverAddress
self.port = port
self.serverRunning = True
threading.Thread.__init__(self)
def run(self):
server_class = BaseHTTPServer.HTTPServer
httpd = server_class((self.serverAddress, self.port), MyHandler)
print time.asctime(), "Server Starts - %s:%s" % (self.serverAddress, self.port)
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()
print time.asctime(), "Server Stops - %s:%s" % (HOST_NAME, PORT_NUMBER)
class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_HEAD(s):
s.send_response(200)
s.send_header("Content-type", "text/html")
s.end_headers()
def do_GET(s):
"""Respond to a GET request."""
if None != re.search('api/v1/nodo/*', s.path):
nodeID = s.path.split('/')[-1]
print 'Solicitando informacion del nodo '+nodeID
s.send_response(200)
s.send_header("Content-type", "text/html")
s.end_headers()
#Prepare JSON with node information
#jsonnode = json.dumps(nodeOjbect.__dict__)
jsonnode = '{ "mac":'+nodeID+', "bat":4.0 }'
s.wfile.write(jsonnode)
if None != re.search('api/v1/st_act/*', s.path):
nodeID = s.path.split('/')[-1]
print 'Solicitando informacion del actuador '+nodeID
s.send_response(200)
s.send_header("Content-type", "text/html")
s.end_headers()
#Prepare JSON with node information
#jsonnode = json.dumps(nodeOjbect.__dict__)
jsonnode = '{ "mac":'+nodeID+', "status":"off" }'
s.wfile.write(jsonnode)
def do_POST(self):
print "ejecutando POST"
if None != re.search('api/v1/act/*', self.path):
ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
if ctype == 'application/json':
length = int(self.headers.getheader('content-length'))
data = cgi.parse_qs(self.rfile.read(length), keep_blank_values=1)
print data
req = json.loads(data.keys()[0])
resCommand = None
#Cant get access to my wsanProtocol!!
#webServer.wsanProtocol.executeCommand(10, resCommand, req.tolist())
print 'Actuacion sobre el nodo ' + req["mac"]
self.send_response(200)
非常感谢!
【问题讨论】:
-
你已经发布了很多不相关的代码,但没有说到底是什么问题。当您尝试调用 zigbee 时会发生什么?
-
不要认为这无关紧要,我正在尝试以 do_POST 方法访问 webServer。当我这样做时,python 失败,告诉我 wsanProtocol 没有 executeCommand 过程。
-
尝试一步一步地推进可测试,而不是构建整个东西,然后发现它不能完全工作。首先,测试你可以做
wsanProtocol.executeCommand(10, something, somethingelse)。然后测试您是否让 Web 服务器正常工作,例如,通过添加调试日志记录。 -
不确定我是否正确 Anton,我已经在另一个基于套接字的服务器中测试了 executeCommand,它可以正常工作。并且网络服务器本身(不调用 executeCommand)也运行良好......问题是无法弄清楚如何在 do_POST 中使 wsanProtocol 可访问