gpt4 book ai didi

python - 将 Node.js 脚本移植到 Python

转载 作者:行者123 更新时间:2023-12-01 02:34:34 25 4
gpt4 key购买 nike

我想将此 Node.js 脚本移植到 Python 中以控制天空盒,https://github.com/dalhundal/sky-remote/blob/master/sky-remote.js

我已经完成了我能做的最好的事情,代码如下;

import time, math, socket, struct, time
from array import array

#sky q port 5900

class remote:
commands={"power": 0, "select": 1, "backup": 2, "dismiss": 2, "channelup": 6, "channeldown": 7, "interactive": 8, "sidebar": 8, "help": 9, "services": 10, "search": 10, "tvguide": 11, "home": 11, "i": 14, "text": 15, "up": 16, "down": 17, "left": 18, "right": 19, "red": 32, "green": 33, "yellow": 34, "blue": 35, 0: 48, 1: 49, 2: 50, 3: 51, 4: 52, 5: 53, 6: 54, 7: 55, 8: 56, 9: 57, "play": 64, "pause": 65, "stop": 66, "record": 67, "fastforward": 69, "rewind": 71, "boxoffice": 240, "sky": 241}
connectTimeout = 1000;

def __init__(self, ip, port=49160):
self.ip=ip
self.port=port

def showCommands(self):
for command, value in self.commands.iteritems():
print str(command)+ " : "+str(value)

def getCommand(self, code):
try:
return self.commands[code]
except:
print "Error: command '"+code+"' is not valid"
return False

def press (self, sequence):
if isinstance(sequence, list):
for item in sequence:
toSend=self.getCommand(item)
if toSend:
self.sendCommand(toSend)
time.sleep(0.5)

else:
toSend=self.getCommand(sequence)
if toSend:
self.sendCommand(toSend)

def sendCommand(self, code):
commandBytes = array('l', [4,1,0,0,0,0, int(math.floor(224 + (code/16))), code % 16])

try:
client=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, msg:
print 'Failed to create socket. Error code: ' + str(msg[0]) + ' , Error message : ' + msg[1]
return

try:
client.connect((self.ip, self.port))
except:
print "Failed to connect to client"
return

l=12
timeout=time.time()+self.connectTimeout

while 1:
data=client.recv(1024)
data=data

if len(data)<24:
client.sendall(data[0:l])
l=1
else:
client.sendall(buffer(commandBytes))
commandBytes[1]=0
client.sendall(buffer(commandBytes))
client.close()
break

if time.time() > timeout:
print "timeout error"
break

我认为问题是如何形成缓冲区?我不完全确定,因为这是我第一次处理缓冲区。阅读了关于 new Buffer 的 Node.js 文档,看起来它创建了一个八位字节数组,而我拥有的是一个整数数组,我可能是错的,但八位字节是 8 位,而整数是 4 位,我已经尝试将数组更改为 long 和 double,但这似乎无法解决问题

最佳答案

我有时间快速阅读了 Node.js 如何处理缓冲区和一般缓冲区,看起来我认为是正确的。

改变;

commandBytes = array('l', [4,1,0,0,0,0, int(math.floor(224 + (code/16))), code % 16])

至;

commandBytes = bytearray([4,1,0,0,0,0, int(math.floor(224 + (code/16))), code % 16])

此外,只需传递字节数组即可;

client.sendall(commandBytes)

而不是;

client.sendall(buffer(commandBytes))

关于python - 将 Node.js 脚本移植到 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46400757/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com