I am writing a program that requires me to lock or disable the mouse pointer on my laptop (like they do in most video games).
Is there a way to lock the mouse pointer in one spot?
Right now, I am using windll.user32.BlockInput(True) to lock the mouse which works for the external USB mouse I have, but not for the touchpad.
Also, I am not making a video game, so I don't really need the mouse input data, but I do want to lock the mouse pointer.
#usage:
# python touchpad.py [OPTIONS]
#
# #example
# python touchpad.py -e
#
# #options:
# -e
# Enables the touchpad
#
# -d
# Disables the touchpad
#
# -s
# Display the touchpad device status
#
# -h
# Help
#
import sys
import subprocess
import re
from optparse import OptionParser
statusFlag = {'--enable': 'Enabled', '--disable': 'Disabled'}
def getDeviceName(deviceId):
data = subprocess.check_output(['xinput', '--list', '--name-only', deviceId])
data = data.decode()
return str(data).rstrip('\n')
# Gets the touch device ID
def getDeviceId():
try:
data = subprocess.check_output(['xinput', '--list'])
except Exception:
print("xinput not found!")
sys.exit();
deviceId = 'none'
for line in data.splitlines():
line = line.lower()
if 'touchpad' in line and 'pointer' in line:
line = line.strip()
match = re.search('id=([0-9]+)', line)
deviceId = str(match.group(1))
#print(deviceId)
#print(line)
if deviceId == 'none':
print('Touch Device not found')
sys.exit();
return deviceId
# Enables / Disables the device
def setEnabled(state):
deviceId = getDeviceId()
flag = 'none'
print("Device Name: %s" % getDeviceName(deviceId))
if state == 'true':
flag = '--enable'
elif state == 'false':
flag = '--disable'
if(flag != 'none'):
try:
subprocess.check_call(['xinput', flag, deviceId])
print('Status: %s' % statusFlag[flag])
except Exception:
print('Device cannot be set to %s' %flag)
# Gets the enable device property for the device Id
def getDeviceProp(deviceId):
propData = subprocess.check_output(['xinput', '--list-props', deviceId])
propData = propData.decode()
for line in propData.splitlines():
if 'Device Enabled' in line:
line = line.strip()
return line[-1]
# Finds the touchpad status and displays the result to screen
def deviceStatus():
deviceId = getDeviceId()
print("Device Name: %s" % getDeviceName(deviceId))
status = getDeviceProp(deviceId)
if status == '0':
print("Status: %s" % statusFlag['--disable'])
elif status == '1':
print("Status: %s" % statusFlag['--enable'])
else:
print("Error can not find device status.")
# Main
def main():
parser = OptionParser(usage="usage: %prog [options]", version="%prog 1.0", description="Example: %prog -e")
parser.add_option("-s", "--status", default=False, action="store_true", help="Display the status of the Touchpad")
parser.add_option("-e", "--enable", default=False, action="store_true", help="Enable Touchpad Device")
parser.add_option("-d", "--disable",default=False, action="store_true", help="Disable Touchpad Device")
(options, args) = parser.parse_args()
if options.status == True:
print("Touchpad device status...")
deviceStatus()
elif options.enable == True:
print("Enabling the Touchpad device...")
setEnabled('true')
elif options.disable == True:
print("Disabling the Touchpad device...")
setEnabled('false')
else:
parser.print_help()
if __name__ == '__main__':
main()
Related
So I am trying to get into using the python library Quarry, but I have had problems with the proxy which is the feature I am trying to use. When I am using the default "proxy_hide_chat.py" example, when I try to load the server in the server list on mc version 1.19.3 it gives this error
No name known for packet: (761, 'status', 'upstream', 0)
Traceback (most recent call last):
File "/home/todd/.local/lib/python3.10/site-packages/quarry/net/protocol.py", line 205, in get_packet_name
return packets.packet_names[key]
KeyError: (761, 'status', 'upstream', 0)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/todd/.local/lib/python3.10/site-packages/quarry/net/protocol.py", line 241, in data_received
name = self.get_packet_name(buff.unpack_varint())
File "/home/todd/.local/lib/python3.10/site-packages/quarry/net/protocol.py", line 207, in get_packet_name
raise ProtocolError("No name known for packet: %s" % (key,))
quarry.net.protocol.ProtocolError: No name known for packet: (761, 'status', 'upstream', 0)
^C[todd#todd minecraftProxy]$ python teleport_proxy.py
Traceback (most recent call last):
File "/home/todd/.local/lib/python3.10/site-packages/twisted/internet/tcp.py", line 1334, in startListening
skt.bind(addr)
OSError: [Errno 98] Address already in use
When I try and connect to the server I get the error "Unknown protocol version" in minecraft.
I have tried to set the protocol version to 761 using this:
factory.protocol_version=761
but it doesn't do anything.
EDIT:
Here is the code:
"""
"Quiet mode" example proxy
Allows a client to turn on "quiet mode" which hides chat messages
This client doesn't handle system messages, and assumes none of them contain chat messages
"""
from twisted.internet import reactor
from quarry.types.uuid import UUID
from quarry.net.proxy import DownstreamFactory, Bridge
class QuietBridge(Bridge):
quiet_mode = False
def packet_upstream_chat_command(self, buff):
command = buff.unpack_string()
if command == "quiet":
self.toggle_quiet_mode()
buff.discard()
else:
buff.restore()
self.upstream.send_packet("chat_command", buff.read())
def packet_upstream_chat_message(self, buff):
buff.save()
chat_message = self.read_chat(buff, "upstream")
self.logger.info(" >> %s" % chat_message)
if chat_message.startswith("/quiet"):
self.toggle_quiet_mode()
elif self.quiet_mode and not chat_message.startswith("/"):
# Don't let the player send chat messages in quiet mode
msg = "Can't send messages while in quiet mode"
self.send_system(msg)
else:
# Pass to upstream
buff.restore()
self.upstream.send_packet("chat_message", buff.read())
def toggle_quiet_mode(self):
# Switch mode
self.quiet_mode = not self.quiet_mode
action = self.quiet_mode and "enabled" or "disabled"
msg = "Quiet mode %s" % action
self.send_system(msg)
def packet_downstream_chat_message(self, buff):
chat_message = self.read_chat(buff, "downstream")
self.logger.info(" :: %s" % chat_message)
# All chat messages on 1.19+ are from players and should be ignored in quiet mode
if self.quiet_mode and self.downstream.protocol_version >= 759:
return
# Ignore message that look like chat when in quiet mode
if chat_message is not None and self.quiet_mode and chat_message.startswith("<"):
return
# Pass to downstream
buff.restore()
self.downstream.send_packet("chat_message", buff.read())
def read_chat(self, buff, direction):
buff.save()
if direction == "upstream":
p_text = buff.unpack_string()
buff.discard()
return p_text
elif direction == "downstream":
# 1.19.1+
if self.downstream.protocol_version >= 760:
p_signed_message = buff.unpack_signed_message()
buff.unpack_varint() # Filter result
p_position = buff.unpack_varint()
p_sender_name = buff.unpack_chat()
buff.discard()
if p_position not in (1, 2): # Ignore system and game info messages
# Sender name is sent separately to the message text
return ":: <%s> %s" % (
p_sender_name, p_signed_message.unsigned_content or p_signed_message.body.message)
return
p_text = buff.unpack_chat().to_string()
# 1.19+
if self.downstream.protocol_version == 759:
p_unsigned_text = buff.unpack_optional(lambda: buff.unpack_chat().to_string())
p_position = buff.unpack_varint()
buff.unpack_uuid() # Sender UUID
p_sender_name = buff.unpack_chat()
buff.discard()
if p_position not in (1, 2): # Ignore system and game info messages
# Sender name is sent separately to the message text
return "<%s> %s" % (p_sender_name, p_unsigned_text or p_text)
elif self.downstream.protocol_version >= 47: # 1.8.x+
p_position = buff.unpack('B')
buff.discard()
if p_position not in (1, 2) and p_text.strip(): # Ignore system and game info messages
return p_text
else:
return p_text
def send_system(self, message):
if self.downstream.protocol_version >= 760: # 1.19.1+
self.downstream.send_packet("system_message",
self.downstream.buff_type.pack_chat(message),
self.downstream.buff_type.pack('?', False)) # Overlay false to put in chat
elif self.downstream.protocol_version == 759: # 1.19
self.downstream.send_packet("system_message",
self.downstream.buff_type.pack_chat(message),
self.downstream.buff_type.pack_varint(1)) # Type 1 for system chat message
else:
self.downstream.send_packet("chat_message",
self.downstream.buff_type.pack_chat(message),
self.downstream.buff_type.pack('B', 0),
self.downstream.buff_type.pack_uuid(UUID(int=0)))
class QuietDownstreamFactory(DownstreamFactory):
bridge_class = QuietBridge
motd = "Proxy Server"
def main(argv):
# Parse options
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-a", "--listen-host", default="0.0.0.0", help="address to listen on")
parser.add_argument("-p", "--listen-port", default=12345, type=int, help="port to listen on")
parser.add_argument("-b", "--connect-host", default="127.0.0.1", help="address to connect to")
parser.add_argument("-q", "--connect-port", default=25565, type=int, help="port to connect to")
args = parser.parse_args(argv)
# Create factory
factory = QuietDownstreamFactory()
factory.connect_host = args.connect_host
factory.connect_port = args.connect_port
# Listen
factory.protocol_version=761
factory.listen(args.listen_host, args.listen_port)
reactor.run()
if __name__ == "__main__":
import sys
main(sys.argv[1:])
Try agan the fctory protocol (for minecraft 1.19) 759
Trying to use the IntradayTickExample code enclosed below. However I kept getting the following message. It says about authorization so I guess its getting stuck in the main. But I have no idea why this wouldn't work as its a BBG example?
My thoughts:
- It exits with code 0 so everything works well.
- It seems to go debug through the code until the authorisation section
- I cant find any way to change anything else r./e. the authorisation
C:\Users\ME\MyNewEnv\Scripts\python.exe F:/ME/BloombergWindowsSDK/Python/v3.12.2/examples/IntradayTickExample.py
IntradayTickExample
Connecting to localhost:8194
TokenGenerationFailure = {
reason = {
source = "apitkns (apiauth) on ebbdbp-ob-596"
category = "NO_AUTH"
errorCode = 12
description = "User not in emrs userid=DBG\ME firm=8787"
subcategory = "INVALID_USER"
}
}
Failed to get token
No authorization
Process finished with exit code 0
And full code below
# IntradayTickExample.py
from __future__ import print_function
from __future__ import absolute_import
import blpapi
import copy
import datetime
from optparse import OptionParser, Option, OptionValueError
TICK_DATA = blpapi.Name("tickData")
COND_CODE = blpapi.Name("conditionCodes")
TICK_SIZE = blpapi.Name("size")
TIME = blpapi.Name("time")
TYPE = blpapi.Name("type")
VALUE = blpapi.Name("value")
RESPONSE_ERROR = blpapi.Name("responseError")
CATEGORY = blpapi.Name("category")
MESSAGE = blpapi.Name("message")
SESSION_TERMINATED = blpapi.Name("SessionTerminated")
TOKEN_SUCCESS = blpapi.Name("TokenGenerationSuccess")
TOKEN_FAILURE = blpapi.Name("TokenGenerationFailure")
AUTHORIZATION_SUCCESS = blpapi.Name("AuthorizationSuccess")
TOKEN = blpapi.Name("token")
def authOptionCallback(option, opt, value, parser):
vals = value.split('=', 1)
if value == "user":
parser.values.auth = "AuthenticationType=OS_LOGON"
elif value == "none":
parser.values.auth = None
elif vals[0] == "app" and len(vals) == 2:
parser.values.auth = "AuthenticationMode=APPLICATION_ONLY;"\
"ApplicationAuthenticationType=APPNAME_AND_KEY;"\
"ApplicationName=" + vals[1]
elif vals[0] == "userapp" and len(vals) == 2:
parser.values.auth = "AuthenticationMode=USER_AND_APPLICATION;"\
"AuthenticationType=OS_LOGON;"\
"ApplicationAuthenticationType=APPNAME_AND_KEY;"\
"ApplicationName=" + vals[1]
elif vals[0] == "dir" and len(vals) == 2:
parser.values.auth = "AuthenticationType=DIRECTORY_SERVICE;"\
"DirSvcPropertyName=" + vals[1]
else:
raise OptionValueError("Invalid auth option '%s'" % value)
def checkDateTime(option, opt, value):
try:
return datetime.datetime.strptime(value, "%Y-%m-%d %H:%M:%S")
except ValueError as ex:
raise OptionValueError(
"option {0}: invalid datetime value: {1} ({2})".format(
opt, value, ex))
class ExampleOption(Option):
TYPES = Option.TYPES + ("datetime",)
TYPE_CHECKER = copy.copy(Option.TYPE_CHECKER)
TYPE_CHECKER["datetime"] = checkDateTime
def parseCmdLine():
parser = OptionParser(description="Retrieve intraday rawticks.",
epilog="Notes: " +
"1) All times are in GMT. " +
"2) Only one security can be specified.",
option_class=ExampleOption)
parser.add_option("-a",
"--ip",
dest="host",
help="server name or IP (default: %default)",
metavar="ipAddress",
default="localhost")
parser.add_option("-p",
dest="port",
type="int",
help="server port (default: %default)",
metavar="tcpPort",
default=8194)
parser.add_option("-s",
dest="security",
help="security (default: %default)",
metavar="security",
default="IBM US Equity")
parser.add_option("-e",
dest="events",
help="events (default: TRADE)",
metavar="event",
action="append",
default=[])
parser.add_option("--sd",
dest="startDateTime",
type="datetime",
help="start date/time (default: %default)",
metavar="startDateTime",
default=None)
parser.add_option("--ed",
dest="endDateTime",
type="datetime",
help="end date/time (default: %default)",
metavar="endDateTime",
default=None)
parser.add_option("--cc",
dest="conditionCodes",
help="include condition codes",
action="store_true",
default=False)
parser.add_option("--auth",
dest="auth",
help="authentication option: "
"user|none|app=<app>|userapp=<app>|dir=<property>"
" (default: %default)",
metavar="option",
action="callback",
callback=authOptionCallback,
type="string",
default="user")
(options, args) = parser.parse_args()
if not options.host:
options.host = ["localhost"]
if not options.events:
options.events = ["TRADE"]
return options
def authorize(authService, identity, session, cid):
tokenEventQueue = blpapi.EventQueue()
session.generateToken(eventQueue=tokenEventQueue)
# Process related response
ev = tokenEventQueue.nextEvent()
token = None
if ev.eventType() == blpapi.Event.TOKEN_STATUS or \
ev.eventType() == blpapi.Event.REQUEST_STATUS:
for msg in ev:
print(msg)
if msg.messageType() == TOKEN_SUCCESS:
token = msg.getElementAsString(TOKEN)
elif msg.messageType() == TOKEN_FAILURE:
break
if not token:
print("Failed to get token")
return False
# Create and fill the authorization request
authRequest = authService.createAuthorizationRequest()
authRequest.set(TOKEN, token)
# Send authorization request to "fill" the Identity
session.sendAuthorizationRequest(authRequest, identity, cid)
# Process related responses
startTime = datetime.datetime.today()
WAIT_TIME_SECONDS = 10
while True:
event = session.nextEvent(WAIT_TIME_SECONDS * 1000)
if event.eventType() == blpapi.Event.RESPONSE or \
event.eventType() == blpapi.Event.REQUEST_STATUS or \
event.eventType() == blpapi.Event.PARTIAL_RESPONSE:
for msg in event:
print(msg)
if msg.messageType() == AUTHORIZATION_SUCCESS:
return True
print("Authorization failed")
return False
endTime = datetime.datetime.today()
if endTime - startTime > datetime.timedelta(seconds=WAIT_TIME_SECONDS):
return False
def printErrorInfo(leadingStr, errorInfo):
print("%s%s (%s)" % (leadingStr, errorInfo.getElementAsString(CATEGORY),
errorInfo.getElementAsString(MESSAGE)))
def processMessage(msg):
data = msg.getElement(TICK_DATA).getElement(TICK_DATA)
print("TIME\t\t\t\tTYPE\tVALUE\t\tSIZE\tCC")
print("----\t\t\t\t----\t-----\t\t----\t--")
for item in data.values():
time = item.getElementAsDatetime(TIME)
timeString = item.getElementAsString(TIME)
type = item.getElementAsString(TYPE)
value = item.getElementAsFloat(VALUE)
size = item.getElementAsInteger(TICK_SIZE)
if item.hasElement(COND_CODE):
cc = item.getElementAsString(COND_CODE)
else:
cc = ""
print("%s\t%s\t%.3f\t\t%d\t%s" % (timeString, type, value, size, cc))
def processResponseEvent(event):
for msg in event:
print(msg)
if msg.hasElement(RESPONSE_ERROR):
printErrorInfo("REQUEST FAILED: ", msg.getElement(RESPONSE_ERROR))
continue
processMessage(msg)
def sendIntradayTickRequest(session, options, identity = None):
refDataService = session.getService("//blp/refdata")
request = refDataService.createRequest("IntradayTickRequest")
# only one security/eventType per request
request.set("security", options.security)
# Add fields to request
eventTypes = request.getElement("eventTypes")
for event in options.events:
eventTypes.appendValue(event)
# All times are in GMT
if not options.startDateTime or not options.endDateTime:
tradedOn = getPreviousTradingDate()
if tradedOn:
startTime = datetime.datetime.combine(tradedOn,
datetime.time(15, 30))
request.set("startDateTime", startTime)
endTime = datetime.datetime.combine(tradedOn,
datetime.time(15, 35))
request.set("endDateTime", endTime)
else:
if options.startDateTime and options.endDateTime:
request.set("startDateTime", options.startDateTime)
request.set("endDateTime", options.endDateTime)
if options.conditionCodes:
request.set("includeConditionCodes", True)
print("Sending Request:", request)
session.sendRequest(request, identity)
def eventLoop(session):
done = False
while not done:
# nextEvent() method below is called with a timeout to let
# the program catch Ctrl-C between arrivals of new events
event = session.nextEvent(500)
if event.eventType() == blpapi.Event.PARTIAL_RESPONSE:
print("Processing Partial Response")
processResponseEvent(event)
elif event.eventType() == blpapi.Event.RESPONSE:
print("Processing Response")
processResponseEvent(event)
done = True
else:
for msg in event:
if event.eventType() == blpapi.Event.SESSION_STATUS:
if msg.messageType() == SESSION_TERMINATED:
done = True
def getPreviousTradingDate():
tradedOn = datetime.date.today()
while True:
try:
tradedOn -= datetime.timedelta(days=1)
except OverflowError:
return None
if tradedOn.weekday() not in [5, 6]:
return tradedOn
def main():
options = parseCmdLine()
# Fill SessionOptions
sessionOptions = blpapi.SessionOptions()
sessionOptions.setServerHost(options.host)
sessionOptions.setServerPort(options.port)
sessionOptions.setAuthenticationOptions(options.auth)
print("Connecting to %s:%s" % (options.host, options.port))
# Create a Session
session = blpapi.Session(sessionOptions)
# Start a Session
if not session.start():
print("Failed to start session.")
return
identity = None
if options.auth:
identity = session.createIdentity()
isAuthorized = False
authServiceName = "//blp/apiauth"
if session.openService(authServiceName):
authService = session.getService(authServiceName)
isAuthorized = authorize(
authService, identity, session,
blpapi.CorrelationId("auth"))
if not isAuthorized:
print("No authorization")
return
try:
# Open service to get historical data from
if not session.openService("//blp/refdata"):
print("Failed to open //blp/refdata")
return
sendIntradayTickRequest(session, options, identity)
print(sendIntradayTickRequest(session, options, identity))
# wait for events from session.
eventLoop(session)
finally:
# Stop the session
session.stop()
if __name__ == "__main__":
print("IntradayTickExample")
try:
main()
except KeyboardInterrupt:
print("Ctrl+C pressed. Stopping...")
__copyright__ = """
Copyright 2012. Bloomberg Finance L.P.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: The above
copyright notice and this permission notice shall be included in all copies
or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
"""
I realized I have been trying to connect to the Server API instead of connectiong to the local terminal. For example, the following code works perfectly:
# SimpleHistoryExample.py
from __future__ import print_function
from __future__ import absolute_import
import blpapi
from optparse import OptionParser
def parseCmdLine():
parser = OptionParser(description="Retrieve reference data.")
parser.add_option("-a",
"--ip",
dest="host",
help="server name or IP (default: %default)",
metavar="ipAddress",
default="localhost")
parser.add_option("-p",
dest="port",
type="int",
help="server port (default: %default)",
metavar="tcpPort",
default=8194)
(options, args) = parser.parse_args()
return options
def main():
options = parseCmdLine()
# Fill SessionOptions
sessionOptions = blpapi.SessionOptions()
sessionOptions.setServerHost(options.host)
sessionOptions.setServerPort(options.port)
print("Connecting to %s:%s" % (options.host, options.port))
# Create a Session
session = blpapi.Session(sessionOptions)
# Start a Session
if not session.start():
print("Failed to start session.")
return
try:
# Open service to get historical data from
if not session.openService("//blp/refdata"):
print("Failed to open //blp/refdata")
return
# Obtain previously opened service
refDataService = session.getService("//blp/refdata")
# Create and fill the request for the historical data
request = refDataService.createRequest("HistoricalDataRequest")
request.getElement("securities").appendValue("EURUSD Curncy")
request.getElement("fields").appendValue("PX_LAST")
request.set("periodicityAdjustment", "ACTUAL")
request.set("periodicitySelection", "DAILY")
request.set("startDate", "20000102")
request.set("endDate", "20191031")
request.set("maxDataPoints", 100000)
print("Sending Request:", request)
# Send the request
session.sendRequest(request)
# Process received events
while(True):
# We provide timeout to give the chance for Ctrl+C handling:
ev = session.nextEvent(500)
for msg in ev:
print(msg)
if ev.eventType() == blpapi.Event.RESPONSE:
# Response completly received, so we could exit
break
finally:
# Stop the session
session.stop()
if __name__ == "__main__":
print("SimpleHistoryExample")
try:
main()
except KeyboardInterrupt:
print("Ctrl+C pressed. Stopping...")
I am new in python. Please help me solve the below problem.
What the meaning of "Invalid argument"?
Below code all are work well but when I add a code publish the live stream through dataplicity. There will occur error "Unable to start capture: Invalid argument i: Error grabbing frames". After the error to publish the live stream, those function below will proceed while motion detection.
The code I add in the top of the def is_person(image) caused error:
os.system('sudo ./mjpg_streamer -i "./input_uvc.so -f 10 -r 640x320 -n -y" -o "./output_http.so -w ./www -p 80"')
def is_person(image):
det = Detector(image)
faces = len(det.face())
print ("FACE: "), det.drawColors[det.drawn-1 % len(det.drawColors)], faces
uppers = len(det.upper_body())
print ("UPPR: "), det.drawColors[det.drawn-1 % len(det.drawColors)], uppers
fulls = len(det.full_body())
print ("FULL: "), det.drawColors[det.drawn-1 % len(det.drawColors)], fulls
peds = len(det.pedestrian())
print ("PEDS: "), det.drawColors[det.drawn-1 % len(det.drawColors)], peds
det.draw()
det.overlay()
return faces + uppers + fulls + peds
# return len(det.face()) or len(det.full_body()) or len(det.upper_body()) # or len(det.pedestrian())
def processImage(imgFile):
global connection
if is_person(imgFile):
print ("True")
imgFile = datetime.datetime.now() .strftime ("%Y-%m-%d-%H.%M.%S.jpg")
cam.capture (imgFile)
#with open(imgFile, "rb") as image_file:
# encoded_string = base64.b64encode(image_file.read())
else: # Not a person
print ("False")
os.remove(imgFile)
sys.exit(0)
try:
while True:
previous_state = current_state
current_state = GPIO.input(sensor)
if current_state != previous_state:
new_state = "HIGH" if current_state else "LOW"
if current_state: # Motion is Detected
lock.acquire()
cam.start_preview() # Comment in future
cam.preview_fullscreen = False
cam.preview_window = (10,10, 320,240)
print('Motion Detected')
for i in range(imgCount):
curTime = (time.strftime("%I:%M:%S")) + ".jpg"
cam.capture(curTime, resize=(320,240))
t = threading.Thread(target=processImage, args = (curTime,))
t.daemon = True
t.start()
time.sleep(frameSleep)
cam.stop_preview()
lock.release()
time.sleep(camSleep)
except KeyboardInterrupt:
cam.stop_preview()
sys.exit(0)
Thank you in advance.
You have an issue with mjpg_streamer configuration.
Check comment #274 here.
I'm struggling to gracefully close a script when the clients send the "stop" command.
As the script is wrote, it actually exit with the following error:
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
self.run()
File "/usr/lib/python3.5/threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
File "server.py", line 248, in start_server
conn, addr = soc.accept()
File "/usr/lib/python3.5/socket.py", line 195, in accept
fd, addr = self._accept()
OSError: [Errno 22] Invalid argument
Any suggestion?
#!/usr/bin/python3
#################################################################################
# BLE PRESENCE FOR DOMOTICZ #
# #
# AUTHOR: MARCO BAGLIVO (ITALY) (https://github.com/mydomo) #
# #
#################################################################################
# BLE_SCAN LIBRARY IS A FORK OF https://github.com/flyinactor91/RasPi-iBeacons #
#################################################################################
#################################################################################
# INSTALL REQUIREMENTS ON UBUNTU SERVER 16.04: #
# #
# sudo apt-get install -y libbluetooth-dev bluez #
# sudo apt-get install python-dev python3-dev python3-setuptools python3-pip #
# sudo pip3 install pybluez #
# #
#################################################################################
import socket
from lib import ble_scan
from threading import Thread
import sys
import os
import time
import bluetooth._bluetooth as bluez
import signal
import subprocess
from collections import OrderedDict
##########- CONFIGURE SCRIPT -##########
socket_ip = '0.0.0.0'
socket_port = 12345
min_inval_between_batt_level_readings = 3600
##########- CONFIGURE TRANSLATIONS -##########
lang_SCAN_STOPPED = 'Scanning stopped by other function'
lang_READING_LOCK = 'Reading in progress...'
lang_READING_START = 'Reading started'
##########- START VARIABLE INITIALIZATION -##########
mode = ''
beacons_detected = ''
batt_lev_detected = ''
scan_beacon_data = True
ble_value = ''
devices_to_analize = {}
batt_lev_detected = {}
read_value_lock = False
##########- END VARIABLE INITIALIZATION -##########
##########- START FUNCTION THAT HANDLE CLIENT INPUT -##########
def socket_input_process(input_string):
global mode
global devices_to_analize
global lang_SCAN_STOPPED
global lang_READING_LOCK
global lang_READING_START
###- TRANSMIT BEACON DATA -###
# check if client requested "beacon_data"
if input_string == 'beacon_data':
# if beacon scanning function has being stopped in order to process one other request (ex.: battery level) warn the client
if scan_beacon_data == False:
return str(lang_SCAN_STOPPED)
# if beacon scanning function is active send the data to the client
if scan_beacon_data == True:
# set operative mode to beacon_data
mode = 'beacon_data'
# return beacons_detected ordered by timestamp ASC (tnx to: JkShaw - http://stackoverflow.com/questions/43715921/python3-ordering-a-complex-dict)
# return "just" the last 300 results to prevent the end of the socket buffer (each beacon data is about 45 bytes)
return str(sorted(beacons_detected.items(), key=lambda x: x[1][1], reverse=True)[:300])
###- TRANSMIT BATTERY LEVEL -###
# check if the request start with battery_level:
if input_string.startswith('battery_level:'):
# trim "battery_level:" from the request
string_devices_to_analize = input_string.replace("battery_level: ", "")
# split each MAC address in a list in order to be processed
devices_to_analize = string_devices_to_analize.split(',')
# set operative mode to battery_level
mode = 'battery_level'
# if the reading has already requested and there is no result ask to wait
if not batt_lev_detected and read_value_lock == True:
return str(lang_READING_LOCK)
# if the reading is requested for the first time start say that will start
elif not batt_lev_detected and read_value_lock == False:
return str(lang_READING_START)
# if is present a battery data send it
else:
return str(batt_lev_detected)
###- STOP RUNNING SERVICES -###
if input_string == 'stop':
killer.kill_now = True
print ('service stopping')
return str('Service stopping')
##########- END FUNCTION THAT HANDLE CLIENT INPUT -##########
##########- START FUNCTION THAT HANDLE SOCKET'S TRANSMISSION -##########
def client_thread(conn, ip, port, MAX_BUFFER_SIZE = 32768):
# the input is in bytes, so decode it
input_from_client_bytes = conn.recv(MAX_BUFFER_SIZE)
# MAX_BUFFER_SIZE is how big the message can be
# this is test if it's too big
siz = sys.getsizeof(input_from_client_bytes)
if siz >= MAX_BUFFER_SIZE:
print("The length of input is probably too long: {}".format(siz))
# decode input and strip the end of line
input_from_client = input_from_client_bytes.decode("utf8").rstrip()
res = socket_input_process(input_from_client)
#print("Result of processing {} is: {}".format(input_from_client, res))
vysl = res.encode("utf8") # encode the result string
conn.sendall(vysl) # send it to client
conn.close() # close connection
##########- END FUNCTION THAT HANDLE SOCKET'S TRANSMISSION -##########
def usb_dongle_reset():
process0 = subprocess.Popen("sudo hciconfig hci0 down", stdout=subprocess.PIPE, shell=True)
process0.communicate()
process1 = subprocess.Popen("sudo hciconfig hci0 reset", stdout=subprocess.PIPE, shell=True)
process1.communicate()
process2 = subprocess.Popen("sudo /etc/init.d/bluetooth restart", stdout=subprocess.PIPE, shell=True)
process2.communicate()
process3 = subprocess.Popen("sudo hciconfig hci0 up", stdout=subprocess.PIPE, shell=True)
process3.communicate()
def ble_scanner():
global beacons_detected
dev_id = 0
usb_dongle_reset()
try:
sock = bluez.hci_open_dev(dev_id)
#print ("ble thread started")
except:
print ("error accessing bluetooth device... restart in progress!")
usb_dongle_reset()
ble_scan.hci_le_set_scan_parameters(sock)
ble_scan.hci_enable_le_scan(sock)
beacons_detected = {}
while (scan_beacon_data == True) and (not killer.kill_now):
try:
returnedList = ble_scan.parse_events(sock, 25)
for beacon in returnedList:
MAC, RSSI, LASTSEEN = beacon.split(',')
beacons_detected[MAC] = [RSSI,LASTSEEN]
time.sleep(1)
except:
print ("failed restarting device... let's try again!")
usb_dongle_reset()
dev_id = 0
sock = bluez.hci_open_dev(dev_id)
ble_scan.hci_le_set_scan_parameters(sock)
ble_scan.hci_enable_le_scan(sock)
time.sleep(1)
def read_battery_level():
global scan_beacon_data
global mode
global batt_lev_detected
global read_value_lock
global min_inval_between_batt_level_readings
uuid_to_check = '0x2a19'
time_difference = 0
while (not killer.kill_now):
if mode == 'battery_level' and read_value_lock == False:
read_value_lock = True
#print ("Dispositivi da analizzare: " + str(devices_to_analize))
for device in devices_to_analize:
device_to_connect = device
#print ("Analizzo dispositivo: " + str(device))
# i'm reading the value stored
battery_level_moderator = str(batt_lev_detected.get(device, "Never"))
# cleaning the value stored
cleaned_battery_level_moderator = str(battery_level_moderator.replace("[", "").replace("]", "").replace(" ", "").replace("'", ""))
# assign the battery level and the timestamp to different variables
if cleaned_battery_level_moderator != "Never":
stored_batterylevel, stored_timestamp = cleaned_battery_level_moderator.split(',')
time_difference = int(time.time()) - int(stored_timestamp)
if (int(min_inval_between_batt_level_readings) <= int(time_difference)) or (str(cleaned_battery_level_moderator) == "Never") or (str(stored_batterylevel) == '255'):
scan_beacon_data = False
usb_dongle_reset()
#PUT HERE THE CODE TO READ THE BATTERY LEVEL
try:
handle_ble = os.popen("sudo hcitool lecc --random " + device_to_connect + " | awk '{print $3}'").read()
handle_ble_connect = os.popen("sudo hcitool ledc " + handle_ble).read()
#ble_value = int(os.popen("sudo gatttool -t random --char-read --uuid " + uuid_to_check + " -b " + device_to_connect + " | awk '{print $4}'").read() ,16)
ble_value = os.popen("sudo gatttool -t random --char-read --uuid " + uuid_to_check + " -b " + device_to_connect + " | awk '{print $4}'").read()
except:
ble_value = 'nd'
if ble_value != '':
ble_value = int(ble_value ,16)
if ble_value == '':
ble_value = '255'
time_checked = str(int(time.time()))
batt_lev_detected[device] = [ble_value,time_checked]
read_value_lock = False
#print (batt_lev_detected)
#AS SOON AS IT FINISH RESTART THE scan_beacon_data PROCESS
scan_beacon_data = True
mode = 'beacon_data'
Thread(target=ble_scanner).start()
time.sleep(1)
def start_server():
global soc
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# this is for easy starting/killing the app
soc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
#print('Socket created')
try:
soc.bind((socket_ip, socket_port))
# print('Socket bind complete')
except socket.error as msg:
# print('Bind failed. Error : ' + str(sys.exc_info()))
sys.exit()
#Start listening on socket
soc.listen(10)
#print('Socket now listening')
# for handling task in separate jobs we need threading
#from threading import Thread
# this will make an infinite loop needed for
# not reseting server for every client
while (not killer.kill_now):
conn, addr = soc.accept()
ip, port = str(addr[0]), str(addr[1])
#print('Accepting connection from ' + ip + ':' + port)
try:
Thread(target=client_thread, args=(conn, ip, port)).start()
except:
print("Terible error!")
import traceback
traceback.print_exc()
soc.close()
def kill_socket():
global soc
global kill_now
kill_socket_switch = False
while (not kill_socket_switch):
if killer.kill_now:
print ("KILL_SOCKET PROVA A CHIUDERE IL SOCKET")
time.sleep(1)
soc.shutdown(socket.SHUT_RDWR)
soc.close()
kill_socket_switch = True
time.sleep(1)
### MAIN PROGRAM ###
class GracefulKiller:
kill_now = False
def __init__(self):
signal.signal(signal.SIGINT, self.exit_gracefully)
signal.signal(signal.SIGTERM, self.exit_gracefully)
def exit_gracefully(self,signum, frame):
global soc
self.kill_now = True
print ('Program stopping...')
if __name__ == '__main__':
killer = GracefulKiller()
Thread(target=start_server).start()
Thread(target=ble_scanner).start()
Thread(target=read_battery_level).start()
Thread(target=kill_socket).start()
# print ("End of the program. I was killed gracefully :)")
I am trying to run Bloomberg example code on my machine. I have created teamviewer VPN to machine where Bloomberg Terminal is installed. I have also disable firewall for both machine.
Bloomberg Terminal is up and logged in.
Code :
# import blpapi
# options = blpapi.SessionOptions()
# options.setServerHost('7.220.156.135')
# options.setServerPort(8194)
# session = blpapi.Session(options)
#
# session.start()
# ContributionsMktdataExample.py
import blpapi
import time
from optparse import OptionParser, OptionValueError
import datetime
import threading
TOKEN_SUCCESS = blpapi.Name("TokenGenerationSuccess")
TOKEN_FAILURE = blpapi.Name("TokenGenerationFailure")
AUTHORIZATION_SUCCESS = blpapi.Name("AuthorizationSuccess")
TOKEN = blpapi.Name("token")
MARKET_DATA = blpapi.Name("MarketData")
SESSION_TERMINATED = blpapi.Name("SessionTerminated")
g_running = True
g_mutex = threading.Lock()
class AuthorizationStatus:
WAITING = 1
AUTHORIZED = 2
FAILED = 3
__metaclass__ = blpapi.utils.MetaClassForClassesWithEnums
g_authorizationStatus = dict()
class MyStream(object):
def __init__(self, id=""):
self.id = id
class MyEventHandler(object):
def processEvent(self, event, session):
global g_running
for msg in event:
print msg
if event.eventType() == blpapi.Event.SESSION_STATUS:
if msg.messageType() == SESSION_TERMINATED:
g_running = False
continue
cids = msg.correlationIds()
with g_mutex:
for cid in cids:
if cid in g_authorizationStatus:
if msg.messageType() == AUTHORIZATION_SUCCESS:
g_authorizationStatus[cid] = \
AuthorizationStatus.AUTHORIZED
else:
g_authorizationStatus[cid] = \
AuthorizationStatus.FAILED
def authOptionCallback(option, opt, value, parser):
vals = value.split('=', 1)
if value == "user":
parser.values.auth = "AuthenticationType=OS_LOGON"
elif value == "none":
parser.values.auth = None
elif vals[0] == "app" and len(vals) == 2:
parser.values.auth = "AuthenticationMode=APPLICATION_ONLY;" \
"ApplicationAuthenticationType=APPNAME_AND_KEY;" \
"ApplicationName=" + vals[1]
elif vals[0] == "userapp" and len(vals) == 2:
parser.values.auth = "AuthenticationMode=USER_AND_APPLICATION;" \
"AuthenticationType=OS_LOGON;" \
"ApplicationAuthenticationType=APPNAME_AND_KEY;" \
"ApplicationName=" + vals[1]
elif vals[0] == "dir" and len(vals) == 2:
parser.values.auth = "AuthenticationType=DIRECTORY_SERVICE;" \
"DirSvcPropertyName=" + vals[1]
else:
raise OptionValueError("Invalid auth option '%s'" % value)
def parseCmdLine():
parser = OptionParser(description="Market data contribution.")
parser.add_option("-a",
"--ip",
dest="hosts",
help="server name or IP (default: localhost)",
metavar="ipAddress",
action="append",
default=[])
parser.add_option("-p",
dest="port",
type="int",
help="server port (default: %default)",
metavar="tcpPort",
default=8194)
parser.add_option("-s",
dest="service",
help="service name (default: %default)",
metavar="service",
default="//blp/mpfbapi")
parser.add_option("-t",
dest="topic",
help="topic (default: %default)",
metavar="topic",
default="/ticker/AUDEUR Curncy")
parser.add_option("--auth",
dest="auth",
help="authentication option: "
"user|none|app=<app>|userapp=<app>|dir=<property>"
" (default: %default)",
metavar="option",
action="callback",
callback=authOptionCallback,
type="string",
default="user")
(options, args) = parser.parse_args()
if not options.hosts:
options.hosts = ["localhost"]
return options
def authorize(authService, identity, session, cid):
with g_mutex:
g_authorizationStatus[cid] = AuthorizationStatus.WAITING
tokenEventQueue = blpapi.EventQueue()
# Generate token
session.generateToken(eventQueue=tokenEventQueue)
# Process related response
ev = tokenEventQueue.nextEvent()
token = None
if ev.eventType() == blpapi.Event.TOKEN_STATUS or \
ev.eventType() == blpapi.Event.REQUEST_STATUS:
for msg in ev:
print msg
if msg.messageType() == TOKEN_SUCCESS:
token = msg.getElementAsString(TOKEN)
elif msg.messageType() == TOKEN_FAILURE:
break
if not token:
print "Failed to get token"
return False
# Create and fill the authorithation request
authRequest = authService.createAuthorizationRequest()
authRequest.set(TOKEN, token)
# Send authorithation request to "fill" the Identity
session.sendAuthorizationRequest(authRequest, identity, cid)
# Process related responses
startTime = datetime.datetime.today()
WAIT_TIME_SECONDS = datetime.timedelta(seconds=10)
while True:
with g_mutex:
if AuthorizationStatus.WAITING != g_authorizationStatus[cid]:
return AuthorizationStatus.AUTHORIZED == \
g_authorizationStatus[cid]
endTime = datetime.datetime.today()
if endTime - startTime > WAIT_TIME_SECONDS:
return False
time.sleep(1)
def main():
options = parseCmdLine()
# Fill SessionOptions
sessionOptions = blpapi.SessionOptions()
for idx, host in enumerate(options.hosts):
sessionOptions.setServerAddress(host, options.port, idx)
sessionOptions.setAuthenticationOptions(options.auth)
sessionOptions.setAutoRestartOnDisconnection(True)
sessionOptions.setNumStartAttempts(len(options.hosts))
myEventHandler = MyEventHandler()
# Create a Session
session = blpapi.ProviderSession(sessionOptions,
myEventHandler.processEvent)
# Start a Session
if not session.start():
print "Failed to start session."
return
providerIdentity = session.createIdentity()
if options.auth:
isAuthorized = False
authServiceName = "//blp/apiauth"
if session.openService(authServiceName):
authService = session.getService(authServiceName)
isAuthorized = authorize(
authService, providerIdentity, session,
blpapi.CorrelationId("auth"))
if not isAuthorized:
print "No authorization"
return
topicList = blpapi.TopicList()
topicList.add(options.service + options.topic,
blpapi.CorrelationId(MyStream(options.topic)))
# Create topics
session.createTopics(topicList,
blpapi.ProviderSession.AUTO_REGISTER_SERVICES,
providerIdentity)
# createTopics() is synchronous, topicList will be updated
# with the results of topic creation (resolution will happen
# under the covers)
streams = []
for i in xrange(topicList.size()):
stream = topicList.correlationIdAt(i).value()
status = topicList.statusAt(i)
topicString = topicList.topicStringAt(i)
if (status == blpapi.TopicList.CREATED):
stream.topic = session.getTopic(topicList.messageAt(i))
streams.append(stream)
else:
print "Stream '%s': topic not resolved, status = %d" % (
stream.id, status)
service = session.getService(options.service)
try:
# Now we will start publishing
value = 1
while streams and g_running:
event = service.createPublishEvent()
eventFormatter = blpapi.EventFormatter(event)
for stream in streams:
value += 1
eventFormatter.appendMessage(MARKET_DATA, stream.topic)
eventFormatter.setElement("BID", 0.5 * value)
eventFormatter.setElement("ASK", value)
for msg in event:
print msg
session.publish(event)
time.sleep(10)
finally:
# Stop the session
session.stop()
if __name__ == "__main__":
print "ContributionsMktdataExample"
try:
main()
except KeyboardInterrupt:
print "Ctrl+C pressed. Stopping..."
__copyright__ = """
Copyright 2012. Bloomberg Finance L.P.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: The above
copyright notice and this permission notice shall be included in all copies
or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
"""
Exception :
ContributionsMktdataExample
23MAY2016_15:50:15.552 6836:4756 ERROR blpapi_platformtransporttcp.cpp:671 blpapi.session.transporttcp.{1}.<7.220.156.135:8194> Connection failed
23MAY2016_15:50:15.552 6836:4756 WARN blpapi_platformcontroller.cpp:371 blpapi.session.platformcontroller.{1} Platform: 0 failed 1 consecutive connect attempts, stopped trying to reconnect.
23MAY2016_15:50:15.552 6836:5612 ERROR blpapi_providersessionimpl.cpp:642 blpapi.providersession.{1} Failed to start provider session: rc=9
Failed to start session.
cmd command :
python main.py --ip=7.220.156.135 --auth=none
It sounds like you're trying to use Desktop APIv3 to get data to your machine from a machine where the Terminal is running. This isn't supported. If you're using Desktop API you can only connect to localhost. The only cases where you can connect to another machine to get Bloomberg data is when using Sever API or B-PIPE.
Even if this were supported, The Desktop API contract states that you can't send Bloomberg data to a different computer.