import socket, ssl, json, struct
# device token returned when the iPhone application
# registers to receive alerts
deviceToken = ''
thePayLoad = {
'aps': {
'alert':'New Images Ready',
'sound':'k1DiveAlarm.caf',
'badge':10,
},
'test_data': { 'foo': 'bar' },
}
# Certificate issued by apple and converted to .pem format with openSSL
theCertfile = 'dev_cerkey_push.pem'
#
theHost = ( 'gateway.sandbox.push.apple.com', 2195 )
#
data = json.dumps( thePayLoad )
# Clear out spaces in the device token and convert to hex
deviceToken = deviceToken.replace(' ','')
byteToken = bytes.fromhex( deviceToken )
theFormat = '!BH32sH%ds' % len(data)
theNotification = struct.pack( theFormat, 0, 32, byteToken, len(data), data.encode() )
# Create our connection using the certfile saved locally
ssl_sock = ssl.wrap_socket( socket.socket( socket.AF_INET, socket.SOCK_STREAM ), certfile = theCertfile )
ssl_sock.connect( theHost )
# Write out our data
ssl_sock.write( theNotification )
# Close the connection -- apple would prefer that we keep
# a connection open and push data as needed.
ssl_sock.close()