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...")
Related
I am trying to request snapshot from Bloomberg through Python API using the example programs that Bloomberg provided with the package. Their own program doesn't work properly and I keep getting the error:
WARN blpapi_subscriptionmanager.cpp:1653 blpapi.session.subscriptionmanager.{1} Subscription management endpoints are required for snapshot request templates but none are available
blpapi.exception.UnsupportedOperationException: No subscription management endpoints for snapshot (0x00080013).
The part of the code that has the snapshot request is in main func:
def main():
"""main entry point"""
global options
options = parseCmdLine()
# Create a session and 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)
print("Connecting to port %d on %s" % (
options.port, ", ".join(options.hosts)))
session = blpapi.Session(sessionOptions)
if not session.start():
print("Failed to start session.")
return
subscriptionIdentity = None
if options.auth:
subscriptionIdentity = session.createIdentity()
isAuthorized = False
authServiceName = "//blp/apiauth"
if session.openService(authServiceName):
authService = session.getService(authServiceName)
isAuthorized = authorize(authService, subscriptionIdentity,
session, blpapi.CorrelationId("auth"))
if not isAuthorized:
print("No authorization")
return
else:
print("Not using authorization")
# Snapshot Request Part:
fieldStr = "?fields=" + ",".join(options.fields)
snapshots = []
nextCorrelationId = 0
for i, topic in enumerate(options.topics):
subscriptionString = options.service + topic + fieldStr
snapshots.append(session.createSnapshotRequestTemplate(
subscriptionString,
subscriptionIdentity,
blpapi.CorrelationId(i)))
nextCorrelationId += 1
requestTemplateAvailable = blpapi.Name('RequestTemplateAvailable')
eventCount = 0
try:
while True:
# Specify timeout to give a chance for Ctrl-C
event = session.nextEvent(1000)
for msg in event:
if event.eventType() == blpapi.Event.ADMIN and \
msg.messageType() == requestTemplateAvailable:
for requestTemplate in snapshots:
session.sendRequestTemplate(
requestTemplate,
blpapi.CorrelationId(nextCorrelationId))
nextCorrelationId += 1
elif event.eventType() == blpapi.Event.RESPONSE or \
event.eventType() == blpapi.Event.PARTIAL_RESPONSE:
cid = msg.correlationIds()[0].value()
print("%s - %s" % (cid, msg))
else:
print(msg)
if event.eventType() == blpapi.Event.RESPONSE:
eventCount += 1
if eventCount >= options.maxEvents:
print("%d events processed, terminating." % eventCount)
break
elif event.eventType() == blpapi.Event.TIMEOUT:
for requestTemplate in snapshots:
session.sendRequestTemplate(
requestTemplate,
blpapi.CorrelationId(nextCorrelationId))
nextCorrelationId += 1
I don't know if endpoint and subscription management endpoint are 2 different things because I have one other code working properly and the endpoint is the IP of the server I am pulling the data.
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()
I'm writing a Ryu a L4 swtich application and i am trying to do the following: when a TCP/UDP packet is identified the application checks in a local database to see if the packet parameters are from a known attacker (source IP, destination IP and destination port).
If the packet matches one logged in the attacker database a flow is added to the switch to drop the specific packet (this flow has a duration of 2 hours), if the packet doesn't match a flow is added to forward to a specific switch port (this flow has a duration of 5 minutes).
The problem is, when the controller sends the new flow to the switch/datapath i receive the following error:
SimpleSwitch13: Exception occurred during handler processing. Backtrace from offending handler [_packet_in_handler] servicing event [EventOFPPacketIn] follows.
Traceback (most recent call last):
File "/root/SecAPI/Code/lib/python3.5/site-packages/ryu/base/app_manager.py", line 290, in _event_loop
handler(ev)
File "/root/SecAPI/Flasks/Code/SDN/switchL3.py", line 237, in _packet_in_handler
self.add_security_flow(datapath, 1, match, actions)
File "/root/SecAPI/Flasks/Code/SDN/switchL3.py", line 109, in add_security_flow
datapath.send_msg(mod)
File "/root/SecAPI/Code/lib/python3.5/site-packages/ryu/controller/controller.py", line 423, in send_msg
msg.serialize()
File "/root/SecAPI/Code/lib/python3.5/site-packages/ryu/ofproto/ofproto_parser.py", line 270, in serialize
self._serialize_body()
File "/root/SecAPI/Code/lib/python3.5/site-packages/ryu/ofproto/ofproto_v1_3_parser.py", line 2738, in _serialize_body
self.out_group, self.flags)
File "/root/SecAPI/Code/lib/python3.5/site-packages/ryu/lib/pack_utils.py", line 25, in msg_pack_into
struct.pack_into(fmt, buf, offset, *args)
struct.error: 'H' format requires 0 <= number <= 65535
heres my full code:
from ryu.base import app_manager
from ryu.controller import ofp_event
from ryu.controller.handler import CONFIG_DISPATCHER, MAIN_DISPATCHER
from ryu.controller.handler import set_ev_cls
from ryu.ofproto import ofproto_v1_3
from ryu.lib.packet import packet
from ryu.lib.packet import ethernet
from ryu.lib.packet import ether_types
from ryu.lib.packet import ipv4
from ryu.lib.packet import tcp
from ryu.lib.packet import udp
from ryu.lib.packet import in_proto
import sqlite3
class SimpleSwitch13(app_manager.RyuApp):
OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION]
def __init__(self, *args, **kwargs):
super(SimpleSwitch13, self).__init__(*args, **kwargs)
self.mac_to_port = {}
self.initial = True
self.security_alert = False
#set_ev_cls(ofp_event.EventOFPSwitchFeatures, CONFIG_DISPATCHER)
def switch_features_handler(self, ev):
datapath = ev.msg.datapath
ofproto = datapath.ofproto
parser = datapath.ofproto_parser
match = parser.OFPMatch()
self.initial = True
actions = [parser.OFPActionOutput(ofproto.OFPP_CONTROLLER,
ofproto.OFPCML_NO_BUFFER)]
self.add_flow(datapath, 0, match, actions)
self.initial = False
# Adds a flow into a specific datapath, with a hard_timeout of 5 minutes.
# Meaning that a certain packet flow ceases existing after 5 minutes.
def add_flow(self, datapath, priority, match, actions, buffer_id=None):
ofproto = datapath.ofproto
parser = datapath.ofproto_parser
inst = [parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS,
actions)]
if buffer_id:
if self.initial == True:
mod = parser.OFPFlowMod(datapath=datapath, buffer_id=buffer_id,
priority=priority, match=match,
instructions=inst)
elif self.initial == False:
mod = parser.OFPFlowMod(datapath=datapath, buffer_id=buffer_id,
priority=priority, match=match,
instructions=inst,hard_timeout=300)
else:
if self.initial == True:
mod = parser.OFPFlowMod(datapath=datapath, priority=priority,
match=match, instructions=inst)
elif self.initial == False:
mod = parser.OFPFlowMod(datapath=datapath, priority=priority,
match=match, instructions=inst,
hard_timeout=300)
datapath.send_msg(mod)
# Adds a security flow into the controlled device, a secured flow differs from a normal
# flow in it's duration, a security flow has a duration of 2 hours.
def add_security_flow(self, datapath, priority, match, actions, buffer_id=None):
ofproto = datapath.ofproto
parser = datapath.ofproto_parser
#inst = [parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS,
# actions)]
inst = [parser.OFPInstructionActions(ofproto.OFPIT_CLEAR_ACTIONS, [])]
if buffer_id:
mod = parser.OFPFlowMod(datapath=datapath, buffer_id=buffer_id,
priority=priority,match=match,command=ofproto.OFPFC_ADD,
instructions=inst, hard_timeout=432000)
else:
mod = parser.OFPFlowMod(datapath=datapath, priority=priority,
match=match, instructions=inst, command=ofproto.OFPFC_ADD,
hard_timeout=432000)
datapath.send_msg(mod)
# Deletes a already existing flow that matches has a given packet match.
def del_flow(self, datapath, priority, match, actions, buffer_id=None):
ofproto = datapath.ofproto
parser = datapath.ofproto_parser
inst = [parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS,
actions)]
if buffer_id:
mod = parser.OFPFlowMod(datapath=datapath,buffer_id=buffer_id,
priority=priority,match=match,instruction=inst,
command=ofproto.OFPFC_DELETE)
else:
mod = parser.OFPFlowMod(datapath=datapath, priority=priority,
match=match, instructions=inst,
command=ofproto.OFPFC_DELETE)
datapath.send_msg(mod)
#set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
def _packet_in_handler(self, ev):
# If you hit this you might want to increase
# the "miss_send_length" of your switch
if ev.msg.msg_len < ev.msg.total_len:
self.logger.debug("packet truncated: only %s of %s bytes",
ev.msg.msg_len, ev.msg.total_len)
msg = ev.msg
datapath = msg.datapath
ofproto = datapath.ofproto
parser = datapath.ofproto_parser
in_port = msg.match['in_port']
pkt = packet.Packet(msg.data)
eth = pkt.get_protocols(ethernet.ethernet)[0]
if eth.ethertype == ether_types.ETH_TYPE_LLDP:
# ignore lldp packet
return
dst = eth.dst
src = eth.src
dpid = datapath.id
self.mac_to_port.setdefault(dpid, {})
self.logger.info("packet in %s %s %s %s", dpid, src, dst, in_port)
# learn a mac address to avoid FLOOD next time.
self.mac_to_port[dpid][src] = in_port
if dst in self.mac_to_port[dpid]:
out_port = self.mac_to_port[dpid][dst]
else:
out_port = ofproto.OFPP_FLOOD
actions = [parser.OFPActionOutput(out_port)]
# install a flow to avoid packet_in next time
if out_port != ofproto.OFPP_FLOOD:
#match = parser.OFPMatch(in_port=in_port, eth_dst=dst, eth_src=src)
# check IP Protocol and create a match for IP
if eth.ethertype == ether_types.ETH_TYPE_IP:
conn = sqlite3.connect("database/sdnDatabase.db")
cursor = conn.cursor()
ip = pkt.get_protocol(ipv4.ipv4)
srcip = ip.src
dstip = ip.dst
#match = parser.OFPMatch(eth_type=ether_types.ETH_TYPE_IP,ipv4_src=srcip,ipv4_dst=dstip)
protocol = ip.proto
# ICMP Protocol
if protocol == in_proto.IPPROTO_ICMP:
print("WARN - We have a ICMP packet")
cursor.execute('select id from knownAttackers where srcaddr = \"{0}\" and dstaddr = \"{1}\" and protocol = "icmp";'.format(srcip, dstip))
result = cursor.fetchall()
match = parser.OFPMatch(eth_type=ether_types.ETH_TYPE_IP, ipv4_src=srcip, ipv4_dst=dstip,
ip_proto=protocol)
if len(result) == 0:
self.security_alert = False
else:
self.security_alert = True
# TCP Protocol
elif protocol == in_proto.IPPROTO_TCP:
print("WARN - We have a TCP packet")
t = pkt.get_protocol(tcp.tcp)
cursor.execute('select id from knownAttackers where srcaddr = \"{0}\" and dstaddr = \"{1}\" and dstport = \"{2}\" and protocol = "tcp";'.format(srcip, dstip, t.dst_port))
result = cursor.fetchall()
match = parser.OFPMatch(eth_type=ether_types.ETH_TYPE_IP, ipv4_src=srcip, ipv4_dst=dstip,
ip_proto=protocol, tcp_dst=t.dst_port)
if len(result) == 0:
self.security_alert = False
else:
print("We have a register in the database for this specific packet: {0}".format(result))
self.security_alert = True
# UDP Protocol
elif protocol == in_proto.IPPROTO_UDP:
print("WARN - We have a UDP packet")
u = pkt.get_protocol(udp.udp)
cursor.execute('select id from knownAttackers where srcaddr = \"{0}\" and dstaddr = \"{1}\" and dstport = \"{2}\" and protocol = "udp";'.format(srcip, dstip, u.dst_port))
result = cursor.fetchall()
match = parser.OFPMatch(eth_type=ether_types.ETH_TYPE_IP, ipv4_src=srcip, ipv4_dst=dstip,
ip_proto=protocol, udp_dst=u.dst_port)
if len(result) == 0:
self.security_alert = False
else:
self.security_alert = True
else:
self.security_alert = False
match = parser.OFPMatch(in_port=in_port, eth_dst=dst, eth_src=src)
# verify if we have a valid buffer_id, if yes avoid to send both
# flow_mod & packet_out
if self.security_alert == False:
if msg.buffer_id != ofproto.OFP_NO_BUFFER:
self.add_flow(datapath, 1, match, actions, msg.buffer_id)
return
else:
self.add_flow(datapath, 1, match, actions)
elif self.security_alert == True:
if msg.buffer_id != ofproto.OFP_NO_BUFFER:
self.add_security_flow(datapath, 1, match, actions, msg.buffer_id)
return
else:
self.add_security_flow(datapath, 1, match, actions)
data = None
if msg.buffer_id == ofproto.OFP_NO_BUFFER:
data = msg.data
if self.security_alert == False:
out = parser.OFPPacketOut(datapath=datapath, buffer_id=msg.buffer_id,
in_port=in_port, actions=actions, data=data)
datapath.send_msg(out)
the above error appears in the end of the add_security_flow() class method when i try to make a TCP connection that is identified as a known attacker, when he tries to send the flow modification (datapath.send_msg(mod)) to the switch/datapath.
What am i doing wrong? Am i'm missing some sort of variable?
In the Ryu controller mailing list a user named IWAMOTO told me that my hard_timeout values was too large for the struct packing (2 hours is 7200 seconds, i dont know where my head was for me to find 432000 haha), after downsizing the hard_timeout to 7200 seconds everything worked out just fine.
Always check the size of the values you're trying to send to a datapath, see if it doesn't exceed 65535.
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.
Background:
I would like to integrate yowsup to my home automation project. I have seen a simple sample on how to receive messages and after some minor changes it is working fine.
Issue:
My problem starts when it comes to integrate the send message feature. Those are the two files I am using:
run.py
from layer import EchoLayer
from yowsup.layers.auth import YowAuthenticationProtocolLayer
from yowsup.layers.protocol_messages import YowMessagesProtocolLayer
from yowsup.layers.protocol_receipts import YowReceiptProtocolLayer
from yowsup.layers.protocol_acks import YowAckProtocolLayer
from yowsup.layers.protocol_presence import YowPresenceProtocolLayer
from yowsup.layers.network import YowNetworkLayer
from yowsup.layers.coder import YowCoderLayer
from yowsup.common import YowConstants
from yowsup.layers import YowLayerEvent
from yowsup.stacks import YowStack, YOWSUP_CORE_LAYERS
from yowsup import env
CREDENTIALS = ("phone", "pwd")
if __name__ == "__main__":
layers = (
EchoLayer,
(YowAuthenticationProtocolLayer, YowMessagesProtocolLayer, YowReceiptProtocolLayer, YowAckProtocolLayer, YowPresenceProtocolLayer)
) + YOWSUP_CORE_LAYERS
stack = YowStack(layers)
# Setting credentials
stack.setProp(YowAuthenticationProtocolLayer.PROP_CREDENTIALS, CREDENTIALS)
# WhatsApp server address
stack.setProp(YowNetworkLayer.PROP_ENDPOINT, YowConstants.ENDPOINTS[0])
stack.setProp(YowCoderLayer.PROP_DOMAIN, YowConstants.DOMAIN)
stack.setProp(YowCoderLayer.PROP_RESOURCE, env.CURRENT_ENV.getResource())
# Sending connecting signal
stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT))
# Program main loop
stack.loop()
layer.py
from yowsup.layers.interface import YowInterfaceLayer, ProtocolEntityCallback
from yowsup.layers.protocol_messages.protocolentities import TextMessageProtocolEntity
from yowsup.layers.protocol_receipts.protocolentities import OutgoingReceiptProtocolEntity
from yowsup.layers.protocol_acks.protocolentities import OutgoingAckProtocolEntity
from yowsup.layers.protocol_presence.protocolentities import PresenceProtocolEntity
import threading
import logging
logger = logging.getLogger(__name__)
class EchoLayer(YowInterfaceLayer):
#ProtocolEntityCallback("message")
def onMessage(self, messageProtocolEntity):
#send receipt otherwise we keep receiving the same message over and over
print str(messageProtocolEntity.getFrom()) + ' - ' + str(messageProtocolEntity.getBody())
receipt = OutgoingReceiptProtocolEntity(messageProtocolEntity.getId(), messageProtocolEntity.getFrom())
self.toLower(receipt)
#ProtocolEntityCallback("send_message")
def sendMessage(self, destination, message, messageProtocolEntity):
outgoingMessageProtocolEntity = TextMessageProtocolEntity(
message,
to = destination + "#s.whatsapp.net")
self.toLower(outgoingMessageProtocolEntity)
#ProtocolEntityCallback("receipt")
def onReceipt(self, entity):
ack = OutgoingAckProtocolEntity(entity.getId(), "receipt", "delivery")
self.toLower(ack)
# List of (jid, message) tuples
PROP_MESSAGES = "org.openwhatsapp.yowsup.prop.sendclient.queue"
def __init__(self):
super(EchoLayer, self).__init__()
self.ackQueue = []
self.lock = threading.Condition()
#ProtocolEntityCallback("success")
def onSuccess(self, successProtocolEntity):
self.lock.acquire()
for target in self.getProp(self.__class__.PROP_MESSAGES, []):
phone, message = target
if '#' in phone:
messageEntity = TextMessageProtocolEntity(message, to = phone)
elif '-' in phone:
messageEntity = TextMessageProtocolEntity(message, to = "%s#g.us" % phone)
else:
messageEntity = TextMessageProtocolEntity(message, to = "%s#s.whatsapp.net" % phone)
self.ackQueue.append(messageEntity.getId())
self.toLower(messageEntity)
self.lock.release()
#ProtocolEntityCallback("ack")
def onAck(self, entity):
self.lock.acquire()
if entity.getId() in self.ackQueue:
self.ackQueue.pop(self.ackQueue.index(entity.getId()))
if not len(self.ackQueue):
logger.info("Message sent")
#raise KeyboardInterrupt()
self.lock.release()
Questions:
Where am I supposed to call the send_message method, so I can send messages wherever I need it?
Is there a regular event (triggering every second or something) which I could use to send my messages?
#ProtocolEntityCallback("send_message")
def sendMessage(self, destination, message, messageProtocolEntity):
outgoingMessageProtocolEntity = TextMessageProtocolEntity(
message,
to = destination + "#s.whatsapp.net")
self.toLower(outgoingMessageProtocolEntity)
In the avove code sendMessage to be called, protocolEntity.getTag() == "send_message" has to be True. You don't need it to send message.
layer.py
from yowsup.layers.interface import YowInterfaceLayer, ProtocolEntityCallback
from yowsup.layers.protocol_messages.protocolentities import TextMessageProtocolEntity
from yowsup.layers.protocol_receipts.protocolentities import OutgoingReceiptProtocolEntity
from yowsup.layers.protocol_acks.protocolentities import OutgoingAckProtocolEntity
from yowsup.layers.protocol_presence.protocolentities import PresenceProtocolEntity
import threading
import logging
logger = logging.getLogger(__name__)
recv_msg = []
class EchoLayer(YowInterfaceLayer):
def __init__(self):
super(EchoLayer, self).__init__()
self.ackQueue = []
self.lock = threading.Condition()
#ProtocolEntityCallback("message")
def onMessage(self, messageProtocolEntity):
if messageProtocolEntity.getType() == 'text':
recv_msg.append((messageProtocolEntity.getFrom(),messageProtocolEntity.getBody()))
#send receipt otherwise we keep receiving the same message over and over
receipt = OutgoingReceiptProtocolEntity(messageProtocolEntity.getId(), messageProtocolEntity.getFrom())
self.toLower(receipt)
#ProtocolEntityCallback("receipt")
def onReceipt(self, entity):
ack = OutgoingAckProtocolEntity(entity.getId(), "receipt", "delivery")
self.toLower(ack)
# List of (jid, message) tuples
PROP_MESSAGES = "org.openwhatsapp.yowsup.prop.sendclient.queue"
#ProtocolEntityCallback("success")
def onSuccess(self, successProtocolEntity):
self.lock.acquire()
for target in self.getProp(self.__class__.PROP_MESSAGES, []):
phone, message = target
if '#' in phone:
messageEntity = TextMessageProtocolEntity(message, to = phone)
elif '-' in phone:
messageEntity = TextMessageProtocolEntity(message, to = "%s#g.us" % phone)
else:
messageEntity = TextMessageProtocolEntity(message, to = "%s#s.whatsapp.net" % phone)
self.ackQueue.append(messageEntity.getId())
self.toLower(messageEntity)
self.lock.release()
#ProtocolEntityCallback("ack")
def onAck(self, entity):
self.lock.acquire()
if entity.getId() in self.ackQueue:
self.ackQueue.pop(self.ackQueue.index(entity.getId()))
if not len(self.ackQueue):
self.lock.release()
logger.info("Message sent")
raise KeyboardInterrupt()
self.lock.release()
To send message define a function send_message in the stack run.py. You can also import run.py and use it's function from other script.
from layer import EchoLayer, recv_msg
CREDENTIALS = ("phone", "pwd")
def send_message(destination, message):
'''
destination is <phone number> without '+'
and with country code of type string,
message is string
e.g send_message('11133434343','hello')
'''
messages = [(destination, message)]
layers = (EchoLayer,
(YowAuthenticationProtocolLayer,
YowMessagesProtocolLayer,
YowReceiptProtocolLayer,
YowAckProtocolLayer,
YowPresenceProtocolLayer)
) + YOWSUP_CORE_LAYERS
stack = YowStack(layers)
stack.setProp(EchoLayer.PROP_MESSAGES, messages)
stack.setProp(YowAuthenticationProtocolLayer.PROP_PASSIVE, True)
# Setting credentials
stack.setProp(YowAuthenticationProtocolLayer.PROP_CREDENTIALS, CREDENTIALS)
# WhatsApp server address
stack.setProp(YowNetworkLayer.PROP_ENDPOINT, YowConstants.ENDPOINTS[0])
stack.setProp(YowCoderLayer.PROP_DOMAIN, YowConstants.DOMAIN)
stack.setProp(YowCoderLayer.PROP_RESOURCE, env.CURRENT_ENV.getResource())
# Sending connecting signal
stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT))
try:
# Program main loop
stack.loop()
except AuthError as e:
print('Authentication error %s' % e.message)
sys.exit(1)
def recv_message():
layers = ( EchoLayer,
(YowAuthenticationProtocolLayer, YowMessagesProtocolLayer,
YowReceiptProtocolLayer, YowAckProtocolLayer,
YowPresenceProtocolLayer)
) + YOWSUP_CORE_LAYERS
stack = YowStack(layers)
# Setting credentials
stack.setProp(YowAuthenticationProtocolLayer.PROP_CREDENTIALS, CREDENTIALS)
# WhatsApp server address
stack.setProp(YowNetworkLayer.PROP_ENDPOINT, YowConstants.ENDPOINTS[0])
stack.setProp(YowCoderLayer.PROP_DOMAIN, YowConstants.DOMAIN)
stack.setProp(YowCoderLayer.PROP_RESOURCE, env.CURRENT_ENV.getResource())
# Sending connecting signal
stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT))
try:
# Program main loop
stack.loop()
except AuthError as e:
print('Authentication error %s' % e.message)
sys.exit(1)
if __name__ == '__main__':
if len(sys.argv) == 1:
print('%s send number message\nrecv\n' % sys.argv[0])
sys.exit(1)
if sys.argv[1] == 'send':
try:
send_message(sys.argv[2],sys.argv[3])
except KeyboardInterrupt:
print('closing')
sys.exit(0)
if sys.argv[1] == 'recv':
try:
recv_message()
except KeyboardInterrupt:
print('closing')
sys.exit(0)
for m in recv_msg:
print('From %s:\n%s\n' % m)
Now you can send message by calling send_message('1234567890','Howdy') and recieve message by calling recv_message().