我想移植这个Node.js脚本来控制Sky框到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
我认为问题是我如何形成缓冲区?我不完全确定这是我第一次处理缓冲区。 阅读了关于新Buffer的Node.js文档后,看起来它创建了一个Octets数组,而我所拥有的是一个int数组,我可能错了,但是Octet是8位,而int是4位,I&#39 ;尝试将数组更改为long和double,但这似乎无法解决问题
答案 0 :(得分:2)
有时间快速了解一下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])
此外,只需传递bytearray;
client.sendall(commandBytes)
而不是;
client.sendall(buffer(commandBytes))