Beispiel #1
0
class Pnub:
    
    def __init__(self, pkey, skey, channel):
        
        # Assign publisher key, subscriber key and channel1
        self.pkey = pkey
        self.skey = skey
        self.channel = channel
        
        # Create pubnub object
        self.pubnub = Pubnub(publish_key = self.pkey, subscribe_key = self.skey)
    
    def callback(self, m):
        #print(m)
        pass
        
    def error(self, m):
        print("Pubnub error:", m)
    
    def publish(self, keys, values):
        
        lenght = len(keys)
        if(lenght != len(values)):
            print("Lists must be of same length!")
            return
        
        json_map = {}
        for i in range(0, lenght):
            json_map[keys[i]] = values[i]
        
        result = json.dumps(json_map)    
        
        self.pubnub.publish(self.channel, result, callback = self.callback, error=self.error)
        
        
class manageGPSLocation(Thread) :

    test = os.environ
    pubnub_publish_key = os.environ['PUBNUB_PUBLISH_KEY']
    pubnub_subscribe_key = os.environ['PUBNUB_SUBSCRIBE_KEY']

    mongodb_connection = None
    collection = None

    def __init__(self):
        Thread.__init__(self)
        mongodb_connection = ConnectionToDatabase()
        manageGPSLocation.collection = mongodb_connection.getCollection("steeds")
        self.pubnub_settings = Pubnub(publish_key=manageGPSLocation.pubnub_publish_key,subscribe_key=manageGPSLocation.pubnub_subscribe_key)
        # Rename to location channel
        self.pubnub_channel = "channel_test"
        self.genericDAO = GenericDAO()

    def subscriber_callback(self, message, channel):
        print(message)
        criteriaDict = {}
        criteriaDict["_id"]=message["_id"]

        updateDict = {}
        subUpdateDict = {}

        subUpdateDict["type"]="Point"
        subUpdateDict["coordinates"] = [message["lng"],message["lat"]]

        updateDict["location"]=subUpdateDict

        self.genericDAO.updateObjects(manageGPSLocation.collection, criteriaDict, updateDict)


    def subscriber_error(self, message):
            print("ERROR : "+message)

    def connect(self, message):
        print("CONNECTED TO LOCATION CHANNEL")

    def reconnect(self, message):
        print("RECONNECTED TO LOCATION CHANNEL")

    def disconnect(self, message):
        print("DISCONNECTED FROM LOCATION CHANNEL")

    def subscribe(self):
        # souscrire au channel
        self.pubnub_settings.subscribe(channels=self.pubnub_channel, callback=self.subscriber_callback, error=self.subscriber_error
                                       ,connect=self.connect, reconnect=self.reconnect, disconnect=self.disconnect)

    def publish(self, message):
        self.pubnub_settings.publish(channel=self.pubnub_channel, message=message)

    def unsubscribe(self):

        # se desinscire du channel
        self.pubnub_settings.unsubscribe(self.pubnub_channel)
Beispiel #3
0
def notify(msg):
    pubnub = Pubnub(
            publish_key=os.getenv('PUBLISH_KEY'),
            subscribe_key=os.getenv('SUBSCRIBE_KEY'),
            pooling=False
    )
    channel = 'service_channel'

    # Synchronous usage
    print pubnub.publish(channel, msg)
def send_to_channel(ch,name,obj):
    from pubnub import Pubnub
    pubnub = Pubnub(publish_key, subscribe_key)
    s=json.dumps(obj)
    dl='-_-_'+str(len(s)+1000000)[1:]
    s=s+dl
    logging.warning(str(len(s)-10)+" "+ str(len(urllib.quote(s.encode("utf-8")))+97)) #pana a 16000…;la 18000 da err
    page_num=name
    for i in xrange(0, len(s), 12000):
        pubnub.publish(ch, name+page_num+str(i+1000000)[1:]+s[i:i+12000], callback= _callback, error= _callback)
class Client:
    command_key = "command"

    def __init__(self, channel):
        self.channel = channel
        # Publish key is the one that usually starts with the "pub-c-" prefix
        publish_key = "pub-c-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
        # Subscribe key is the one that usually starts with the "sub-c" prefix
        # Do not forget to replace the string with your subscribe key
        subscribe_key = "sub-c-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
        self.pubnub = Pubnub(publish_key=publish_key, subscribe_key=subscribe_key)
        self.pubnub.subscribe(channels=self.channel,
                              callback=self.callback,
                              error=self.callback,
                              connect=self.connect,
                              reconnect=self.reconnect,
                              disconnect=self.disconnect)

    def callback_command_message(self, message):
        print("I've received the following response from PubNub cloud: {0}".format(message))

    def error_command_message(self, message):
        print("There was an error when working with the PubNub cloud: {0}".format(message))

    def publish_command(self, command_name, key, value):
        command_message = {
            self.__class__.command_key: command_name,
            key: value}
        self.pubnub.publish(
            channel=self.channel,
            message=command_message,
            callback=self.callback_command_message,
            error=self.error_command_message)

    def callback(self, message, channel):
        if channel == self.channel:
            print("I've received the following message: {0}".format(message))

    def error(self, message):
        print("Error: " + str(message))

    def connect(self, message):
        print("Connected to the {0} channel".
              format(self.channel))
        print(self.pubnub.publish(
            channel=self.channel,
            message="Listening to messages in the PubNub Python Client"))

    def reconnect(self, message):
        print("Reconnected to the {0} channel".
              format(self.channel))

    def disconnect(self, message):
        print("Disconnected from the {0} channel".
              format(self.channel))
class manageClients(Thread) :

    test = os.environ
    pubnub_publish_key = os.environ['PUBNUB_PUBLISH_KEY']
    pubnub_subscribe_key = os.environ['PUBNUB_SUBSCRIBE_KEY']

    mongodb_connection = None
    collection = None

    def __init__(self):
        Thread.__init__(self)
        mongodb_connection = ConnectionToDatabase()
        manageClients.deliveries_collection = mongodb_connection.getCollection("temp_deliveries")
        self.pubnub_settings = Pubnub(publish_key=manageClients.pubnub_publish_key,subscribe_key=manageClients.pubnub_subscribe_key)
        # Rename to location channel
        self.pubnub_channel = "clients_channel"
        self.genericDAO = GenericDAO()
        self.manageSteeds = manageSteeds()

    def subscriber_callback(self, message, channel):
        print(message)

        # Inserer la demande de livraison faite par le client
        if(message["msg_code"] == "XX") :
            # inserer la demande de livraison dans une collection temporaire
            id_delivery = self.genericDAO.insertObject(manageClients.deliveries_collection, message)




    def subscriber_error(self, message):
            print("ERROR : "+message)

    def connect(self, message):
        print("CONNECTED TO LOCATION CHANNEL")

    def reconnect(self, message):
        print("RECONNECTED TO LOCATION CHANNEL")

    def disconnect(self, message):
        print("DISCONNECTED FROM LOCATION CHANNEL")

    def subscribe(self):
        # souscrire au channel
        self.pubnub_settings.subscribe(channels=self.pubnub_channel, callback=self.subscriber_callback, error=self.subscriber_error
                                       ,connect=self.connect, reconnect=self.reconnect, disconnect=self.disconnect)

    def publish(self, message):
        self.pubnub_settings.publish(channel=self.pubnub_channel, message=message)

    def unsubscribe(self):

        # se desinscire du channel
        self.pubnub_settings.unsubscribe(self.pubnub_channel)
class ImagePublisher(object):

    def __init__(self):
        self.pubnub = Pubnub(
            publish_key=PUBNUB_PUBLISH_KEY,
            subscribe_key=PUBNUB_SUBSCRIBE_KEY,
            cipher_key='',
            ssl_on=False)

    def publish_frame(self, jpeg_frame):
        message = base64.b64encode(jpeg_frame)
        self.pubnub.publish(PUBLISH_CHANNEL, message)
Beispiel #8
0
def main():
    publish_key = os.environ['PUBNUB_PUBLISH_KEY']
    subscribe_key = os.environ['PUBNUB_SUBSCRIBE_KEY']
    pubnub = Pubnub(publish_key, subscribe_key, ssl_on=False)
    try:
        cpu = system.SystemInfo()
        while True:
            pubnub.publish(channel="kiettv.raspberry.os", message=cpu.get_cpu_percent(), callback=None, error=callback)
            time.sleep(1)
    except KeyboardInterrupt:
        pubnub.unsubscribe(channel='kiettv.raspberry.os')
        exit(0)
Beispiel #9
0
def _send_image_back_to_user(phone_num_or_email, watermark_image_url):
    if COMPANY_SETTINGS["web_flow"]:
        # TODO vars need renaming
        pubnub = Pubnub(
            publish_key=PUBNUB_PUBLISH_KEY,
            subscribe_key=PUBNUB_SUBSCRIBE_KEY,
        )
        pubnub.publish(phone_num_or_email, watermark_image_url)

    elif COMPANY_SETTINGS["sms_photos"]:
        ImageTexter().text_image(phone_num_or_email, watermark_image_url)

    elif COMPANY_SETTINGS["email_photos"]:
        ImageEmailer().email_image(phone_num_or_email, watermark_image_url)
class PiBusHub(object):
  def __init__(self):
    self.logger = logging.getLogger(__name__)
    if not hasattr(cfg, 'PUBNUB_CHANNEL_KEY'):
      self.logger.debug("PubNub[ChannelKey] not defined - PubNub support disabled")
    if not hasattr(cfg, 'PUBNUB_PUBLISH_KEY'):
      self.logger.debug("PubNub[PublishKey] not defined - PubNub support disabled")
      return
    if cfg.PUBNUB_PUBLISH_KEY == '':
      self.logger.debug("PubNub[PublishKey] not configured - PubNub support disabled")
      return

    if not hasattr(cfg, 'PUBNUB_SUBSCRIBE_KEY'):
      self.logger.debug("PubNub[SubscribeKey] not defined - PubNub support disabled")
      return

    self.logger.debug("PubNub registering: " +cfg.PUBNUB_PUBLISH_KEY + " : " + cfg.PUBNUB_SUBSCRIBE_KEY)

    self.pubnub = Pubnub(publish_key=cfg.PUBNUB_PUBLISH_KEY, subscribe_key=cfg.PUBNUB_SUBSCRIBE_KEY)
    
    
    if cfg.PUBNUB_SUBSCRIBE_KEY != '':
      self.logger.info("PubNub subscribing: " + cfg.PUBNUB_CHANNEL_KEY)
      self.pubnub.subscribe(channels=cfg.PUBNUB_CHANNEL_KEY, callback=self.callback, error=self.error, connect=self.connect, reconnect=self.reconnect, disconnect=self.disconnect)


  def callback(self, message, channel):
    print("CALLBACK: " + message +":" + channel)
  
  
  def error(message):
    print("ERROR : " + str(message))
  
  
  def connect(self, channel):
    print("CONNECTED: " +channel)
    self.pubnub.publish(channel='Mongo', message='Hello from the PubNub Python SDK')
  
  
  
  def reconnect(message):
    print("RECONNECTED:" + message)
  
  
  def disconnect(message):
    print("DISCONNECTED:" + message)

  def publish(self, message):
    print("PUBLISH:" + message)
    self.pubnub.publish(channel=cfg.PUBNUB_CHANNEL_KEY, message=message)
class MyPubnubConn():

    def __init__(self, channel):
        self.conn = Pubnub(publish_key=publish_key, subscribe_key=subscribe_key, ssl_on=True,
                           # cipherkey randomly generated for purposes of PoC, but it is too short and needs to be
                           #   securely stored.
                           # cipher_key=cipher_key
                           )
        self.channel = channel
        self.subscribed = threading.Event()

        # server doesn't need to subscribe, only publish
        #self.conn.subscribe(channels=self.channel, callback=self.incoming_message, error=self.error_cb,
        #                     connect=self.connect_cb, reconnect=self.reconnect_cb, disconnect=self.disconnect_cb)

    def incoming_message(self, message, channel):
        pass
        #print(message)

    def error_cb(self, message):
        pass
        #print("\tERROR : " + str(message))

    def connect_cb(self, message):
        self.subscribed.set()

    def reconnect_cb(self, message):
        self.subscribed.set()
        #print("\tRECONNECTED")

    def disconnect_cb(self, message):
        self.subscribed.clear()
        #print("\tDISCONNECTED")

    def send_cb(self, message):
        pass

    def discontinue(self):
        self.conn.unsubscribe(channel=self.channel)

    def publish(self, message):
        self.conn.publish(channel=self.channel, message=message, callback=self.send_cb, error=self.error_cb)

    def wait_until_ready(self):
        self.subscribed.wait()

    def print_status(self):
        print("\nCurrently connected to channel '%s'" % self.channel)
def send_message(app, message):
   app.logger.debug("Publish message {} to channel {}".format(message, PUBNUB_CHANNEL))

   client = Pubnub(publish_key=app.config['PUBNUB_PUBLISH'],
                   subscribe_key=app.config['PUBNUB_SUBSCRIBER'])
   return client.publish(channel=PUBNUB_CHANNEL,
                         message=message)
class WorkspaceSensor:
    def __init__(self,setting_file_path):
        with open(setting_file_path) as f:
            self._setting = json.load(f,"utf-8")

        self._circuit = circuit.parse(self._setting["GPIO"])
        self._current_status = self._circuit.get_status()

        self._on_resistance = Resistance(self._setting["on_resistance"],1,self._update_status)
        self._off_resistance = Resistance(self._setting["off_resistance"],0,self._update_status)

        self._pubnub = Pubnub(publish_key=self._setting["publish_key"], subscribe_key=self._setting["subscribe_key"])
        self._pubnub.subscribe(channels='plzcast_' + self._setting["group"], callback=self._callback_plzcast,connect=self._callback_connect, reconnect=self._callback_connect)

    def run(self):
        while True:
            sensor_status = self._circuit.get_status()
            if(sensor_status == 1):
                self._on_resistance.load()
                self._off_resistance.clear()
            else:
                self._off_resistance.load()
                self._on_resistance.clear()

            time.sleep(self._setting["duration"])

    def _send(self):
        message=json.dumps({
            "floor":self._setting["floor"],
            "id":self._setting["id"],
            "name":self._setting["name"],
            "status":self._current_status
        })

        self._pubnub.publish(channel='wkstatus_' + self._setting["group"],message=message)

    def _callback_plzcast(self,message,channel):
        self._send()

    def _callback_connect(self,message):
        self._send()

    def _update_status(self,new_status):
        if(new_status != self._current_status):
            self._current_status = new_status
            self._send()
Beispiel #14
0
class iotbridge(object):
    def __init__(self, publish_key,
        subscribe_key,uuid):
 
        self.publish_key = publish_key
        self.subscribe_key = subscribe_key
        self.uuid = uuid
        self.pubnub = Pubnub( 'demo', 'demo', None, False)
        self.pubnub.uuid = self.uuid
    
    
    
    def send(self, channel, message):
        # Sending message on the channel
        self.pubnub.publish(channel, message)
 
    def connect(self, channel, callback):
        # Listening for messages on the channel
        self.pubnub.subscribe(channel, callback=callback)
Beispiel #15
0
class Net:
    def callback(self, message):
        print(message)

    def __init__(self, channel = "Channel-ux8kwdv1u"):
        self.channel = channel
        self.pubnub = Pubnub(publish_key=PUB_KEY,
                subscribe_key=SUB_KEY)

    def subscribe(self, callback):
        self.pubnub.subscribe(channels=self.channel,
                callback=callback, error=self.callback)

    def unsubscribe(self):
        self.pubnub.unsubscribe(channel=self.channel)

    def publish(self, message):
        self.pubnub.publish(channel=self.channel, message=message,
                callback=self.callback, error=self.callback)
Beispiel #16
0
class CloudPubNub(CloudServiceBase):
    """
    PubNub cloud service connector
    """
    def __init__(self, publish_key, subscribe_key, strategy=None):
        """

        :param publish_key: Publish key
        :type publish_key: str.
        :param subscribe_key: Subscribe key
        :type subscribe_key: str
        :param strategy: Strategy object to send data to cloud.
        :type strategy: StrategyBase.
        """
        super(CloudPubNub, self).__init__(strategy=strategy)
        self.name = 'pubnub'
        self.pubnub = Pubnub(publish_key=publish_key, subscribe_key=subscribe_key)
        self.pubnub.subscribe(channels="iot_data", callback=self._callback_subscribe, error=self._error)

    @staticmethod
    def _callback_subscribe(message, channel):
        """
        Callback method for subscribe.
        """
        logging.info('PubNub reads: {}'.format(message))

    @staticmethod
    def _error(message):
        """
        Error method for subscribe.
        """
        logging.error('PubNub: {}'.format(message))

    @staticmethod
    def _callback_publish(message):
        """
        Callback method for publish.
        """
        logging.info('PubNub: {}'.format(message))

    def _send_data(self, data, device_name):
        self.pubnub.publish("iot_data", data, callback=self._callback_publish, error=self._callback_publish)
    def post(self):
        """ User sends gold and route info to server.
        Request
            uid - user_id
            cid - channel_id
            data - message
        """
        data = json.loads(self.request.body)
        uid = data['uid']
        print uid
        cid = data['cid']
        print cid
        ucg = data['current_gold']
        print "The user's current gold is " + ucg
        r = data['route']
        print "The route is: " + r

        pointsList = r.split(";")
        ndb.GeoPoint()
        rid = uid + "-" + cid
        route = Route(route_id=rid, list_of_points=[])
        for i in range(len(pointsList)):
            lng = pointsList[i].split()[0]
            lat = pointsList[i].split()[1]
            route.list_of_points.append(ndb.GeoPoint(lng, lat))
        route.put()
        usid = uid + "-" + cid
        user_session = UserSession(user_session_id=usid, base_point="",
                                   drop_off_point="", user_current_gold=ucg, route_id=rid)
        user_session.put()
        # session = Session.query(Session.channel_id == cid).get()
        pubnub = Pubnub(publish_key=PUBLISH_KEY,
                        subscribe_key=SUBSCRIBE_KEY, ssl_on=False, uuid=str(uid))
        pubnub.subscribe(cid, callback)
        pubnub.publish(cid, uid + " has selected a route")
        response = {'user-session-id': usid}
        self.response.out.write(json.dumps(response))
Beispiel #18
0
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('longitude', required=True)
        parser.add_argument('latitude', required=True)
        parser.add_argument('upload_time', required=False)

        args = parser.parse_args()

        user = User(args['longitude'], args['latitude'], args['upload_time'])
        db.session.add(user)
        db.session.commit()

        pubnub = Pubnub(
            publish_key="pub-c-d15beef1-3112-44a9-9bf2-7995a8311b1d",
            subscribe_key="sub-c-4449a38e-9ce9-11e5-8db0-0619f8945a4f"
        )

        pubnub.publish(
            'Channel-n6vdjcnlr',
            '{"message": "Got new update"}', callback=self.callback, error=self.callback
        )


        return {"message": "Success"}
Beispiel #19
0
class dashjazz(object):
    def __init__(self, publish_key,
        subscribe_key,uuid):

        self.publish_key = publish_key
        self.subscribe_key = subscribe_key
        self.uuid = uuid
        self.pubnub = Pubnub( 'demo', 'demo', None, False)
        self.pubnub.uuid = self.uuid
    
    
    
    def send(self, channel, message):
        # Sending message on the channel
        self.pubnub.publish({
            'channel' : channel,
            'message' : message})

    def connect(self, channel, receiver):
        # Listening for messages on the channel
        self.pubnub.subscribe({
            'channel' : channel,
            'callback' : receiver
        })
import os
import time
import sys
from pubnub import Pubnub
import Adafruit_DHT as dht

pubnub = Pubnub(publish_key='pub-c-156a6d5f-22bd-4a13-848d-b5b4d4b36695',
                subscribe_key='sub-c-f762fb78-2724-11e4-a4df-02ee2ddab7fe')
channel = 'tempeon'


def callback(message):
    print(message)


#published in this fashion to comply with Eon
while True:
    h, t = dht.read_retry(dht.DHT22, 4)
    print 'Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(t, h)
    pubnub.publish(
        'tempeon',
        {'columns': [['x', time.time()], ['temperature_celcius', t]]})
    pubnub.publish('humeon', {'columns': [['humidity', h]]})
Beispiel #21
0
from pubnub import Pubnub

pubnub=Pubnub(publish_key='pub-c-519554a2-0a6b-4154-8516-4b7f1b7ad3d5',subscribe_key='sub-c-f29517fc-0332-11e6-861b-02ee2ddab7fe')

def _callback(message):
	print(message)

def _error(message):
	print(message)
while(1):
	pubnub.publish('ch2','Hi from me',callback=_callback,error=_error)

Beispiel #22
0
class manageSteeds(Thread):

    test = os.environ
    pubnub_publish_key = os.environ['PUBNUB_PUBLISH_KEY']
    pubnub_subscribe_key = os.environ['PUBNUB_SUBSCRIBE_KEY']

    mongodb_connection = None
    collection = None

    def __init__(self):
        Thread.__init__(self)
        mongodb_connection = ConnectionToDatabase()

        self.steeds_collection = mongodb_connection.getCollection(
            "available_steeds")
        self.deliveries_collection = mongodb_connection.getCollection(
            "temp_deliveries")
        self.deliveries_steeds_collection = mongodb_connection.getCollection(
            "temp_deliveries_steeds")

        self.pubnub_settings = Pubnub(
            publish_key=manageSteeds.pubnub_publish_key,
            subscribe_key=manageSteeds.pubnub_subscribe_key)
        # Rename to location channel
        self.pubnub_channel = "steeds_channel"

        self.genericDAO = GenericDAO()

        self.scheduler = sched.scheduler()  # Instansiate a scheduler

    def subscriber_callback(self, message, channel):
        x = 1

    def subscriber_error(self, message):
        print("ERROR : " + message)

    def connect(self, message):
        print("CONNECTED TO STEEDS CHANNEL")

    def reconnect(self, message):
        print("RECONNECTED TO STEEDS CHANNEL")

    def disconnect(self, message):
        print("DISCONNECTED FROM STEEDS CHANNEL")

    def subscribe(self):
        # souscrire au channel
        self.pubnub_settings.subscribe(channels=self.pubnub_channel,
                                       callback=self.subscriber_callback,
                                       error=self.subscriber_error,
                                       connect=self.connect,
                                       reconnect=self.reconnect,
                                       disconnect=self.disconnect)

    def publish(self, message):
        self.pubnub_settings.publish(channel=self.pubnub_channel,
                                     message=message)

    def unsubscribe(self):

        # se desinscire du channel
        self.pubnub_settings.unsubscribe(self.pubnub_channel)
# how to instansiate a scheduler

#Out of Pubnub functions

    def manageClientDeliveryRequest(self, iddelivery):

        # Search delivery by id (criteria)
        delivery_criteria = {}
        delivery_criteria["_id"] = iddelivery

        temp_delivery = self.genericDAO.getOneObject(
            self, self.deliveries_colllection, delivery_criteria)

        #Extract pickup coordinates from temporary delivery
        client_coordinates = [
            temp_delivery["pickup_lng"], temp_delivery["pickup_lat"]
        ]

        # Get nearest steeds to pickup location
        nearest_steeds = self.genericDAO.getNearestSteeds(
            self, self.steeds_collection, client_coordinates)

        # Save available steeds for delivery
        delivery_steeds = {}
        delivery_steeds["iddelivery"] = iddelivery
        delivery_steeds["available_steeds"] = nearest_steeds

        self.genericDAO.insertObject(self.deliveries_steeds_collection,
                                     delivery_steeds)

        #Send delivery request to seeder
        self.sendDeliveryRequestToSteed(iddelivery)

    def sendDeliveryRequestToSteed(self, iddelivery):

        # Search delivery by id (criteria)
        delivery_criteria = {}
        delivery_criteria["_id"] = iddelivery

        temp_delivery = self.genericDAO.getOneObject(
            self, self.deliveries_colllection, delivery_criteria)

        #Check received_positive_response field
        received_response = temp_delivery["received_positive_response"]

        if (not (received_response)):

            #Search available steeds for delivery
            delivery_steeds_criteria = {}
            delivery_steeds_criteria["iddelivery"] = iddelivery

            available_steeds = self.genericDAO.getOneObject(
                self, self.deliveries_steeds_collection,
                delivery_steeds_criteria)

            #Send steed delivery request
            self.publish("XXXX" + iddelivery + available_steeds[0]["_id"] +
                         " " + "Other delivery details")

            #Delete 1st steed from available steeds list
            new_available_steeds = available_steeds[1:len(available_steeds) -
                                                    1]

            #Update delivery available steeds

            update_search_criteria = {}
            update_search_criteria["iddelivery"] = iddelivery

            update_field = {}
            update_field["available_steeds"] = new_available_steeds

            #Add update function to Generic DAO from old projects

            #Schedule method call
            self.scheduler.enter(10, 1,
                                 self.sendDeliveryRequestToSteed(iddelivery))
            self.scheduler.run()
Beispiel #23
0
class Server(Thread):
    def __init__(self, url, keepAlive=False, sendReceipts=False):
        super(Server, self).__init__()
        self.sendReceipts = sendReceipts
        self.keepAlive = keepAlive
        self.db = create_engine(url,
                                echo=False,
                                pool_size=10,
                                pool_timeout=600,
                                pool_recycle=300)

        self.Session = sessionmaker(bind=self.db)
        self.s = self.Session()
        self.job = None

        self.pubnub = Pubnub(os.environ['PUB_KEY'], os.environ['SUB_KEY'],
                             None, False)

        self.timeout = int(os.getenv('TIMEOUT', 3600))
        connectionManager = YowsupConnectionManager(self.timeout)

        connectionManager.setAutoPong(keepAlive)

        self.signalsInterface = connectionManager.getSignalsInterface()
        self.methodsInterface = connectionManager.getMethodsInterface()

        self.signalsInterface.registerListener("message_received",
                                               self.onMessageReceived)
        self.signalsInterface.registerListener("group_messageReceived",
                                               self.onGroupMessageReceived)
        self.signalsInterface.registerListener("image_received",
                                               self.onImageReceived)
        self.signalsInterface.registerListener("video_received",
                                               self.onVideoReceived)
        self.signalsInterface.registerListener("audio_received",
                                               self.onAudioReceived)
        self.signalsInterface.registerListener("vcard_received",
                                               self.onVCardReceived)
        self.signalsInterface.registerListener("location_received",
                                               self.onLocationReceived)
        self.signalsInterface.registerListener("receipt_messageSent",
                                               self.onReceiptMessageSent)
        self.signalsInterface.registerListener("receipt_messageDelivered",
                                               self.onReceiptMessageDelivered)

        self.signalsInterface.registerListener("auth_success",
                                               self.onAuthSuccess)
        self.signalsInterface.registerListener("auth_fail", self.onAuthFailed)
        self.signalsInterface.registerListener("disconnected",
                                               self.onDisconnected)

        self.signalsInterface.registerListener("contact_gotProfilePicture",
                                               self.onGotProfilePicture)
        self.signalsInterface.registerListener("profile_setStatusSuccess",
                                               self.onSetStatusSuccess)
        self.signalsInterface.registerListener("group_createSuccess",
                                               self.onGroupCreateSuccess)
        self.signalsInterface.registerListener("group_createFail",
                                               self.onGroupCreateFail)
        self.signalsInterface.registerListener("group_gotInfo",
                                               self.onGroupGotInfo)
        self.signalsInterface.registerListener(
            "group_addParticipantsSuccess", self.onGroupAddParticipantsSuccess)
        self.signalsInterface.registerListener(
            "group_removeParticipantsSuccess",
            self.onGroupRemoveParticipantsSuccess)
        self.signalsInterface.registerListener("group_imageReceived",
                                               self.onGroupImageReceived)

        self.signalsInterface.registerListener("group_subjectReceived",
                                               self.onGroupSubjectReceived)
        self.signalsInterface.registerListener(
            "notification_removedFromGroup",
            self.onNotificationRemovedFromGroup)
        self.signalsInterface.registerListener(
            "notification_groupParticipantAdded",
            self.onNotificationGroupParticipantAdded)
        self.signalsInterface.registerListener("group_gotParticipants",
                                               self.onGotGroupParticipants)

        self.signalsInterface.registerListener("media_uploadRequestSuccess",
                                               self.onUploadRequestSuccess)
        # self.signalsInterface.registerListener("media_uploadRequestFailed", self.onUploadRequestFailed)
        self.signalsInterface.registerListener("media_uploadRequestDuplicate",
                                               self.onUploadRequestDuplicate)
        self.signalsInterface.registerListener("presence_available",
                                               self.onPresenceAvailable)
        self.signalsInterface.registerListener("presence_unavailable",
                                               self.onPresenceUnavailable)

        self.cm = connectionManager
        self.url = os.environ['URL']

        self.post_headers = {
            'Content-type': 'application/json',
            'Accept': 'application/json'
        }
        self.done = False

    def onUploadFailed(self, hash):
        print "Upload failed"

    def login(self, username, password, id):
        self.username = username
        self.password = password
        self.account_id = id
        self.use_realtime = os.environ['USE_REALTIME'] == "true"
        self.pubnub_channel = os.environ['PUB_CHANNEL'] + "_%s" % self.username

        self._d("Logging in")
        self.methodsInterface.call("auth_login",
                                   (self.username, self.password))
        self.methodsInterface.call("presence_sendAvailable", ())

    def run(self):
        while not self.done:
            self.seekJobs()
            time.sleep(2)

    def _formatContacts(self, raw):
        contacts = raw.split(",")
        for i, _ in enumerate(contacts):
            contacts[i] = contacts[i] + "@s.whatsapp.net"
        return contacts

    def _formatContact(self, phone_number):
        return phone_number + "@s.whatsapp.net"

    def seekJobs(self):
        jobs = self.s.query(Job).filter_by(sent=False,
                                           account_id=self.account_id,
                                           pending=False).all()
        if len(jobs) > 0:
            self._d("Pending Jobs %s" % len(jobs))

        acc = self._getAccount()
        self._d("Offline : %s" % acc.off_line, True)

        for job in jobs:
            if self._onSchedule(job.scheduled_time) and acc.off_line == False:
                self._d("Calling %s" % job.method)
                job.runs += 1

                if job.off_line == True:
                    account = self._getAccount()
                    account.off_line = True

                    job.sent = True
                    self.job = job

                    self.s.commit()
                    self.cm.disconnect("Disconnecting for offline jobs")
                else:
                    if job.method == "group_create":
                        res = self.methodsInterface.call(
                            job.method, (job.args, ))
                        job.sent = True
                    elif job.method == "group_end":
                        res = self.methodsInterface.call(
                            job.method, (job.args, ))
                        job.sent = True
                    elif job.method == "group_addParticipants":
                        self.methodsInterface.call(job.method, (
                            job.targets,
                            self._formatContacts(job.args),
                        ))
                        job.sent = True
                    elif job.method == "group_removeParticipants":
                        # params = job.args.split(",")
                        self.methodsInterface.call(job.method, (
                            job.targets,
                            self._formatContacts(job.args),
                        ))
                        job.sent = True
                    elif job.method == "group_getParticipants":
                        self.methodsInterface.call('group_getParticipants',
                                                   (job.targets, ))
                        job.sent = True
                    elif job.method == "contact_getProfilePicture":
                        self.methodsInterface.call("contact_getProfilePicture",
                                                   (job.args, ))
                        job.sent = True
                    elif job.method == "sendMessage":

                        if job.simulate == True:
                            self.methodsInterface.call("typing_send",
                                                       (job.targets, ))
                            self.methodsInterface.call("typing_paused",
                                                       (job.targets, ))

                        job.whatsapp_message_id = self.sendMessage(
                            job.targets, job.args)
                        job.sent = True
                    elif job.method == "broadcast_Text":
                        jids = job.targets.split(",")
                        targets = []
                        for jid in jids:
                            targets.append("*****@*****.**" % jid)
                        job.whatsapp_message_id = self.methodsInterface.call(
                            "message_broadcast", (
                                targets,
                                job.args,
                            ))

                        job.sent = True
                    elif job.method == "uploadMedia":
                        asset = self.s.query(Asset).get(job.asset_id)

                        if asset.mms_url == None:
                            self.requestMediaUrl(asset)
                        else:
                            # find the jobs after this
                            next_job = self.s.query(Job).filter_by(
                                id=job.next_job_id, pending=True).first()
                            next_job.pending = False
                        job.sent = True
                    elif job.method == "sendImage":
                        asset = self._getAsset(job.args)
                        targets = job.targets
                        if "@" not in targets:
                            targets = targets + "@s.whatsapp.net"
                        job.whatsapp_message_id = self.sendImage(
                            targets, asset)
                        job.sent = True
                    elif job.method == "sendVideo":
                        asset = self.s.query(Asset).get(job.asset_id)
                        job.whatsapp_message_id = self.sendVideo(
                            job.targets, asset)
                        job.sent = True
                    elif job.method == "sendContact":
                        jids = job.targets.split(",")
                        for jid in jids:
                            self.sendVCard(jid, job.args)
                        job.sent = True
                    elif job.method == "sendAudio":
                        asset = self.s.query(Asset).get(job.asset_id)
                        self.sendAudio(job.targets + "@s.whatsapp.net", asset)
                        job.sent = True
                    elif job.method == "broadcast_Video":
                        args = job.args.split(",")
                        asset = self._getAsset(job.args)
                        jids = job.targets.split(",")
                        for jid in jids:
                            self.sendVideo(jid + "@s.whatsapp.net", asset)
                            time.sleep(1)
                        job.sent = True
                    elif job.method == "broadcast_Group_Image":
                        asset = self._getAsset(job.args)
                        self.sendImage(job.targets, asset)
                        job.sent = True
                    elif job.method == "broadcast_Group_Video":
                        asset = self._getAsset(job.args)
                        self.sendVideo(job.targets, asset)
                        job.sent = True
                    elif job.method == "sendLocation":
                        location = self.s.query(Location).get(job.args)
                        self.sendLocation(job.targets, location)
                        job.sent = True
        if acc.off_line == True and self.job == None:
            self._d("Reconnecting")

            acc = self._getAccount()
            acc.off_line = False
            self.s.commit()

            self.methodsInterface.call("auth_login",
                                       (self.username, self.password))
            self.methodsInterface.call("presence_sendAvailable", ())

        self.s.commit()

    def _d(self, message, debug=False):
        if debug == False:
            logging.info("%s - %s" % (self.username, message))
        else:
            logging.debug("%s - %s" % (self.username, message))

    def _onSchedule(self, scheduled_time):
        return (scheduled_time is None
                or datetime.now() > self.utc_to_local(scheduled_time))

    def _getContact(self, phone_number):
        return self.s.query(Contact).filter_by(
            account_id=self.account_id, phone_number=phone_number).scalar()

    def _getAccount(self):
        return self.s.query(Account).get(self.account_id)

    def _getAsset(self, args):
        args = args.split(",")
        asset_id = args[0]
        return self.s.query(Asset).get(asset_id)

    def _sendRealtime(self, message):
        if self.use_realtime:
            self.pubnub.publish({
                'channel': self.pubnub_channel,
                'account': self.username,
                'message': message
            })

    def onReceiptMessageDelivered(self, jid, messageId):
        self._d("Delivered %s" % messageId)
        self._d("From %s" % jid)
        # self.s.query(Job).filter_by(sent=False).all()

        session = self.Session()
        job = session.query(Job).filter_by(
            sent=True, whatsapp_message_id=messageId).scalar()
        if job is not None:
            job.received = True
            session.commit()

            if job.method == "sendMessage" or job.method == "sendImage":
                m = session.query(Message).get(job.message_id)
                self._d("Looking for message with id to send a receipt %s" %
                        job.message_id)
                if m is not None:
                    m.received = True
                    m.receipt_timestamp = datetime.now()
                    session.commit()

                    data = {"receipt": {"message_id": m.id}}
                    self._post("/receipt", data)

                    self._sendRealtime({'type': 'receipt', 'message_id': m.id})
            else:
                data = {
                    "receipt": {
                        "message_id": messageId,
                        "phone_number": jid.split("@")[0]
                    }
                }
                self._post("/broadcast_receipt", data)

    def onReceiptMessageSent(self, jid, messageId):
        self._d("Sent %s" % messageId)
        self._d("To %s" % jid)

    def onPresenceAvailable(self, jid):
        self._d("JID available %s" % jid)
        phone_number = jid.split("@")[0]
        contact = self._getContact(phone_number)

        if contact is not None:
            url = "/contacts/%s" % contact.id
            self._patch(url, {"contact": {"last_seen": str(datetime.now())}})

    def onPresenceUnavailable(self, jid, last):
        self._d("JID unavilable %s" % jid)
        self._d("Last seen is %s" % last)

        if last == "deny":
            self._d("this number %s has blocked you" % jid)

    def onUploadRequestDuplicate(self, _hash, url):
        self._d("Upload duplicate")
        self._d("The url is %s" % url)
        self._d("The hash is %s" % _hash)

        asset = self.s.query(Asset).filter_by(asset_hash=_hash).order_by(
            desc(Asset.id)).first()
        self._d("Asset id %s" % asset.mms_url)
        asset.mms_url = url
        self.s.commit()

        self._sendAsset(asset.id)

        put_url = "/assets/%s" % asset.id
        data = {"asset": {"mms_url": url}}
        self._patch(put_url, data)

    def utc_to_local(self, utc_dt):
        # get integer timestamp to avoid precision lost
        timestamp = calendar.timegm(utc_dt.timetuple())
        local_dt = datetime.fromtimestamp(timestamp)
        assert utc_dt.resolution >= timedelta(microseconds=1)
        return local_dt.replace(microsecond=utc_dt.microsecond)

    def onUploadRequestSuccess(self, _hash, url, removeFrom):
        self._d("Upload Request success")
        self._d("The url is %s" % url)
        self._d("The hash is %s" % _hash)
        asset = self.s.query(Asset).filter_by(asset_hash=_hash).order_by(
            desc(Asset.id)).first()
        asset.mms_url = url
        self.s.commit()

        path = self.getImageFile(asset)

        self._d("To upload %s" % path)
        self._d("To %s" % self.username)

        MU = MediaUploader(self.username + "@s.whatsapp.net",
                           self.username + "@s.whatsapp.net",
                           self.onUploadSucccess, self.onUploadError,
                           self.onUploadProgress)

        self._d("Path %s" % path)
        self._d("Url %s" % url)

        MU.upload(path, url, asset.id)

    def _sendAsset(self, asset_id):
        self._d("Sending an uploaded asset %s" % asset_id)
        upload_jobs = self.s.query(Job).filter_by(asset_id=asset_id,
                                                  method="uploadMedia",
                                                  sent=True).all()
        self._d("Found %s jobs tied to this asset" % len(upload_jobs))
        for job in upload_jobs:
            self._d("Found job with sent %s" % job.sent)
            self._d("Found job %s - %s " % (job.id, job.next_job_id))
            if job.next_job_id is not None:
                next_job = self.s.query(Job).get(job.next_job_id)
                if next_job.pending == True and next_job.sent == False:
                    next_job.pending = False

        self.s.commit()

    def onUploadSucccess(self, url, _id):
        self._d("Upload success!")
        self._d("Url %s" % url)
        if _id is not None:
            asset = self.s.query(Asset).get(_id)
            asset.mms_url = url

            self.s.commit()
            self._sendAsset(asset.id)

    def onUploadError(self):
        self._d("Error with upload")

    def onUploadProgress(self, progress):
        self._d("Upload Progress")

    def _link(self, url):
        if url is not None and not url.startswith("http"):
            return os.environ['URL'] + url
        else:
            return url

    def requestMediaUrl(self, asset):
        self._d("About to request for Asset %s" % asset.id)
        self._d("Requesting Url: %s" % asset.url)
        mtype = asset.asset_type.lower()
        sha1 = hashlib.sha256()

        url = self._link(asset.url)
        preview = self._link(asset.preview_url)
        self._d("Full url : %s" % url)
        self._d("Preview url: %s" % preview)

        file_name = self.getImageFile(asset)

        self._d("File name: %s" % file_name)

        fp = open(file_name, 'wb')
        fp.write(requests.get(url).content)
        fp.close()

        self._d("Written file to %s" % file_name)

        if asset.asset_type != "Audio":
            tb_path = self.getImageThumbnailFile(asset)
            tb = open(tb_path, 'wb')
            self._d("Preview URL %s" % preview)
            tb.write(requests.get(preview).content)
            tb.close()
            self._d("Written thumbnail path : %s" % tb_path)

        fp = open(file_name, 'rb')
        try:
            sha1.update(fp.read())
            hsh = base64.b64encode(sha1.digest())

            asset.asset_hash = hsh
            self.s.commit()

            rst = self.methodsInterface.call(
                "media_requestUpload",
                (hsh, mtype, os.path.getsize(file_name)))
            self._d("Requested media upload for %s" % asset.id)
        finally:
            fp.close()

    def getImageFile(self, asset):
        if asset.asset_type == "Image":
            path = "_%s" % asset.id + asset.name
            file_name = "tmp/%s" % path
            return file_name
        elif asset.asset_type == "Video":
            path = "_%s" % asset.id + asset.name
            file_name = "tmp/%s.mp4" % path
            self._d("Image filename %s" % file_name)
            return file_name
        elif asset.asset_type == "Audio":
            path = "_%s" % asset.id + asset.name
            file_name = "tmp/%s" % path
            return file_name

    def getImageThumbnailFile(self, asset):
        if asset.asset_type == "Image":
            path = "_%s" % asset.id + "_thumb_" + asset.name
            file_name = "tmp/%s" % path
            return file_name
        else:
            path = "_%s" % asset.id + "_thumb_" + asset.name
            file_name = "tmp/%s.jpg" % path
            return file_name

    def sendVideo(self, target, asset):
        self._d("In sendVideo %s" % asset.id)
        thumbnail = self.getImageThumbnailFile(asset)
        self._d("The thumbnail %s" % thumbnail)

        f = open(thumbnail, 'r')
        stream = base64.b64encode(f.read())
        f.close()
        rst = self.methodsInterface.call(
            "message_videoSend",
            (target, asset.mms_url, "Video",
             str(os.path.getsize(self.getImageThumbnailFile(asset))), stream))
        self._d("Called video send %s" % rst)
        return rst

    def sendVCard(self, target, args):
        account = self.s.query(Account).get(self.account_id)

        card = vobject.vCard()
        params = args.split(",")
        family_name = params[0]
        given_name = params[1]
        name = family_name + " " + given_name

        card.add('fn')
        card.fn.value = name

        card.add('n')
        card.n.value = vobject.vcard.Name(family=family_name, given=given_name)

        self._d("First name %s" % family_name)
        self._d("Last name %s" % given_name)

        api_url = self.url + "/api/v1/base/status?token=%s" % account.auth_token
        headers = {
            'Content-type': 'application/json',
            'Accept': 'application/json'
        }
        r = requests.get(api_url, headers=headers)
        response = r.json()

        del params[0]
        del params[0]

        for number in params:
            tel = number.split(":")
            num = card.add('tel')
            num.value = tel[1]
            num.type_param = tel[0]

        self._d("Response is %s" % response)
        if response['profile_pic'] != self.url + '/blank-profile.png':
            tb = open('tmp/profile_thumb.jpg', 'wb')
            tb.write(requests.get(response['profile_pic']).content)
            tb.close()

            f = open('tmp/profile_thumb.jpg', 'r')
            stream = base64.b64encode(f.read())
            f.close()

            card.add('photo')
            card.photo.value = stream
            card.photo.type_param = "JPEG"
            # card.photo.encoding_param = "b"

        self._d("Data %s" % card.serialize())
        self.methodsInterface.call("message_vcardSend",
                                   (target, card.serialize(), name))

    def sendAudio(self, target, asset):
        self._d("Sending %s" % asset.mms_url)
        self._d("To %s" % target)
        self._d("Name %s" % asset.name)
        self._d("Size %s" % asset.audio_file_size)
        rst = self.methodsInterface.call(
            "message_audioSend",
            (target, asset.mms_url, asset.name, str(asset.audio_file_size)))
        return rst

    def sendImage(self, target, asset):
        f = open(self.getImageThumbnailFile(asset), 'r')
        stream = base64.b64encode(f.read())
        f.close()
        self._d("Target %s" % target)
        self._d("URL %s" % asset.mms_url)
        self._d("URL %s" % asset.asset_hash)
        rst = self.methodsInterface.call(
            "message_imageSend",
            (target, asset.mms_url, "Image",
             str(os.path.getsize(self.getImageThumbnailFile(asset))), stream))
        self._d("Result of send image %s" % rst)
        return rst

    def sendMessage(self, target, text):
        self._d("Message %s" % text)
        jid = target
        self._d("To %s" % jid)
        rst = self.methodsInterface.call("message_send", (jid, text))
        return rst

    def sendLocation(self, target, location):
        self._d("Sending location %s,%s to %s" %
                (str(location.latitude), str(location.longitude), target))
        jid = self._formatContact(target)
        # message_locationSend(str jid,float latitude,float longitude,str preview)

        rst = self.methodsInterface.call(
            "message_locationSend", (jid, str(
                location.latitude), str(location.longitude), location.preview))
        return rst

    def onGroupSubjectReceived(self, messageId, jid, author, subject,
                               timestamp, receiptRequested):
        self._d("Group subject received")
        if receiptRequested and self.sendReceipts:
            self.methodsInterface.call("message_ack", (jid, messageId))

        data = {"name": subject, "group_type": "External", "jid": jid}
        self._post("/groups", data)
        self._d("Updated the group")

    def onGroupAddParticipantsSuccess(self, groupJid, jid):
        self._d("Added participant %s" % jid)
        # check the profile pic
        self.checkProfilePic(jid[0])

    def onGroupRemoveParticipantsSuccess(self, groupJid, jid):
        self._d("Removed participant %s" % jid)

    def onNotificationGroupParticipantAdded(self, groupJid, jid):
        self._d("Group participant added %s" % jid)
        data = {"groupJid": groupJid, "phone_number": jid.split("@")[0]}

        self._post("/groups/add_member", data)

    def onNotificationRemovedFromGroup(self, groupJid, jid):
        self._d("You were removed from the group %s" % groupJid)

        put_url = self.url + "/groups/remove_member"
        data = {"groupJid": groupJid, 'phone_number': jid.split("@")[0]}
        self._post("/groups/remove_member", data)
        self._d("Updated the group")

    def onGotGroupParticipants(self, groupJid, jids):
        self._d("Got group participants")

        data = {"groupJid": groupJid, "jids": jids}
        self._post("/groups/update_membership", data)

    def onGroupCreateSuccess(self, groupJid):
        self._d("Created with id %s" % groupJid)
        self.methodsInterface.call("group_getInfo", (groupJid, ))

    def onGroupGotInfo(self, jid, owner, subject, subjectOwner,
                       subjectTimestamp, creationTimestamp):
        self._d("Group info %s - %s" % (jid, subject))

        data = {"name": subject, "jid": jid}
        self._post("/update_group", data)
        self._d("Updated the group %s" % subject)

        create_job = self.s.query(Job).filter_by(method="group_create",
                                                 args=subject).first()
        if create_job.next_job_id is not None:
            next_job = self.s.query(Job).get(create_job.next_job_id)

            self._d("Next job %s" % next_job.id)
            self._d("Next job sent? %s" % next_job.sent)
            self._d("Next job runs? %s" % next_job.runs)
            if next_job.method == "group_addParticipants" and next_job.sent == True and next_job.runs == 0:
                next_job.sent = False
                next_job.targets = jid
                self.s.commit()

    def onGroupCreateFail(self, errorCode):
        self._d("Error creating a group %s" % errorCode)

    def onSetStatusSuccess(self, jid, messageId):
        self._d("Set the profile message for %s - %s" % (jid, messageId))

    def onAuthSuccess(self, username):
        self._d("We are authenticated")
        self.methodsInterface.call("ready")
        self.setStatus(1, "Authenticated")

    def setStatus(self, status, message="Status message"):
        self._d("Setting status %s" % status)
        data = {"status": status, "message": message}
        self._post("/status", data)

    def onAuthFailed(self, username, err):
        self._d("Authentication failed for %s" % username)
        self._post("/wa_auth_error", {})

    def _postOffline(self, args):
        url = os.environ['API_URL']
        headers = {
            'Content-type': 'application/json',
            'Accept': 'application/json'
        }
        params = {
            "nickname": account.name,
            "password": account.whatsapp_password,
            "jid": account.phone_number
        }
        r = requests.post(url, data=dict(params.items() + args.items()))
        return r

    def onDisconnected(self, reason):
        self._d("Disconnected! Reason: %s" % reason)
        self.setStatus(0, "Got disconnected")

        account = self.s.query(Account).get(self.account_id)
        if account.off_line == False:
            self._d('About to log in again with %s and %s' %
                    (self.username, self.password))
            self._d('Unscheduled outtage for this number')

            rollbar.report_message(
                'Unscheduled outage for %s - %s' %
                (self.username, account.name), 'warning')
            self._d(
                'Going to wait for a few minutes before trying to log in again'
            )
            time.sleep(15)
            self.login(self.username, self.password, self.account_id)
        elif account.off_line == True and self.job is not None:
            # call the current job
            job = self.job
            url = os.environ['API_URL']
            headers = {
                'Content-type': 'application/json',
                'Accept': 'application/json'
            }
            if job.method == "profile_setStatus":
                args = {
                    "nickname": account.name,
                    "method": job.method,
                    "password": account.whatsapp_password,
                    "status": job.args,
                    "jid": account.phone_number
                }
                r = requests.post(url, data=args)
                self._d(r.text)
            elif job.method == "setProfilePicture":
                ret = self._postOffline({
                    "method": job.method,
                    "image_url": job.args
                })
                self._d(ret.text)
            elif job.method == "broadcast_Image":
                image_url = job.args.split(",")[1]
                full_url = os.environ['URL'] + image_url
                self._d(full_url)
                args = {
                    "nickname": account.name,
                    "targets": job.targets,
                    "method": job.method,
                    "password": account.whatsapp_password,
                    "image": full_url,
                    "jid": account.phone_number,
                    "externalId": job.id
                }

                r = requests.post(url, data=args)
                self._d(r.text)

            self.job = None
            # account.off_line = False
            self.s.commit()

    def onGotProfilePicture(self, jid, imageId, filePath):
        self._d('Got profile picture')
        url = self.url + "/contacts/" + jid.split(
            "@")[0] + "/upload?account=" + self.username
        files = {'file': open(filePath, 'rb')}
        r = requests.post(url, files=files)

    def checkProfilePic(self, jid):
        pull_pic = os.environ['PULL_STATUS_PIC']
        if pull_pic == "true":
            phone_number = jid.split("@")[0]
            get_url = self.url + "/profile?phone_number=" + phone_number + "&account=" + self.username
            headers = {
                'Content-type': 'application/json',
                'Accept': 'application/json'
            }
            r = requests.get(get_url, headers=headers)
            response = r.json()

            if response['profile_url'] == '/missing.jpg':
                self.methodsInterface.call("contact_getProfilePicture",
                                           (jid, ))

    def onGroupMessageReceived(self, messageId, jid, author, content,
                               timestamp, wantsReceipt, pushName):
        self._d('Received a message on the group %s' % content)
        self._d('JID %s - %s - %s' % (jid, pushName, author))

        if wantsReceipt and self.sendReceipts:
            self.methodsInterface.call("message_ack", (jid, messageId))

        data = {
            "message": {
                "text": content,
                "group_jid": jid,
                "message_type": "Text",
                "whatsapp_message_id": messageId,
                "name": pushName,
                "jid": author
            }
        }
        self._post("/receive_broadcast", data)

        self.checkProfilePic(author)
        self._sendRealtime({
            'type': 'text',
            'phone_number': jid,
            'text': content,
            'name': pushName
        })

    def _patch(self, url, data):
        data.update(account=self.username)
        headers = {
            'Content-type': 'application/json',
            'Accept': 'application/json'
        }
        r = requests.patch(self.url + url,
                           data=json.dumps(data),
                           headers=headers)

    def _post(self, url, data):
        data.update(account=self.username)
        headers = {
            'Content-type': 'application/json',
            'Accept': 'application/json'
        }
        r = requests.post(self.url + url,
                          data=json.dumps(data),
                          headers=headers)

    def onMessageReceived(self, messageId, jid, messageContent, timestamp,
                          wantsReceipt, pushName, isBroadCast):
        self._d('Message Received %s' % messageContent)
        phone_number = jid.split("@")[0]

        if wantsReceipt and self.sendReceipts:
            self.methodsInterface.call("message_ack", (jid, messageId))

        data = {
            "message": {
                "text": messageContent,
                "phone_number": phone_number,
                "message_type": "Text",
                "whatsapp_message_id": messageId,
                "name": pushName
            }
        }
        self._post("/messages", data)

        self._sendRealtime({
            'type': 'text',
            'phone_number': phone_number,
            'text': messageContent,
            'name': pushName
        })

        self.checkProfilePic(jid)

    def onLocationReceived(self, messageId, jid, name, preview, latitude,
                           longitude, wantsReceipt, isBroadcast):
        self._d('Location Received')
        phone_number = jid.split("@")[0]

        if wantsReceipt and self.sendReceipts:
            self.methodsInterface.call("message_ack", (jid, messageId))

        data = {
            "location": {
                'latitude': latitude,
                'longitude': longitude,
                'preview': preview,
                'phone_number': phone_number,
                "whatsapp_message_id": messageId,
                'name': name
            }
        }
        self._post("/locations", data)

    def onImageReceived(self, messageId, jid, preview, url, size, wantsReceipt,
                        isBroadCast):
        self._d('Image Received')
        phone_number = jid.split("@")[0]

        data = {
            "message": {
                'url': url,
                'message_type': 'Image',
                'phone_number': phone_number,
                "whatsapp_message_id": messageId,
                'name': ''
            }
        }
        self._post("/upload", data)

        if wantsReceipt and self.sendReceipts:
            self.methodsInterface.call("message_ack", (jid, messageId))

        self._sendRealtime({
            'type': 'image',
            'phone_number': phone_number,
            'url': url,
            'name': ''
        })

        self.checkProfilePic(jid)

    def onGroupImageReceived(self, messageId, jid, author, preview, url, size,
                             wantsReceipt):
        phone_number = author.split("@")[0]
        self._d("Group image received %s - %s - %s - %s " %
                (messageId, jid, phone_number, url))

        if wantsReceipt and self.sendReceipts:
            self.methodsInterface.call("message_ack", (jid, messageId))

        data = {
            "message": {
                'url': url,
                'message_type': 'Image',
                'phone_number': phone_number,
                'group_jid': jid,
                "whatsapp_message_id": messageId,
                'name': ''
            }
        }
        self._post("/upload", data)

        self._sendRealtime({
            'type': 'image',
            'group_jid': jid,
            'url': url,
            'from': phone_number
        })

    def onVCardReceived(self, messageId, jid, name, data, wantsReceipt,
                        isBroadcast):
        vcard = vobject.readOne(data)
        vcard.prettyPrint()

        data = {
            "vcard": {
                'phone_number': jid.split("@")[0],
                'whatsapp_message_id': messageId,
                'data': vcard.serialize()
            }
        }
        self._post("/vcards", data)

        if wantsReceipt and self.sendReceipts:
            self.methodsInterface.call("message_ack", (jid, messageId))

    def onAudioReceived(self, messageId, jid, url, size, wantsReceipt,
                        isBroadcast):
        self._d("Audio received %s" % messageId)
        self._d("url: %s" % url)
        phone_number = jid.split("@")[0]

        data = {
            "message": {
                'url': url,
                'message_type': 'Audio',
                'phone_number': phone_number,
                "whatsapp_message_id": messageId,
                'name': ''
            }
        }
        self._post("/upload", data)

        if wantsReceipt and self.sendReceipts:
            self.methodsInterface.call("message_ack", (jid, messageId))

    def onVideoReceived(self, messageId, jid, mediaPreview, mediaUrl,
                        mediaSize, wantsReceipt, isBroadcast):
        self._d("Video Received %s" % messageId)
        self._d("From %s" % jid)
        self._d("url: %s" % mediaUrl)

        phone_number = jid.split("@")[0]
        data = {
            "message": {
                'url': mediaUrl,
                'message_type': 'Video',
                'phone_number': phone_number,
                "whatsapp_message_id": messageId,
                'name': ''
            }
        }
        self._post("/upload", data)

        # Send a receipt regardless of whether it was a successful upload
        if wantsReceipt and self.sendReceipts:
            self.methodsInterface.call("message_ack", (jid, messageId))
        # r = requests.post(post_url, data=json.dumps(data), headers=headers)

    def onGotProfilePicture(self, jid, imageId, filePath):
        self._d('Profile picture received')
        url = self.url + "/contacts/" + jid.split(
            "@")[0] + "/upload?account=" + self.username
        files = {'file': open(filePath, 'rb')}
        r = requests.post(url, files=files)
        cmd <<= 1
        GPIO.output(spi_clk, True)
        GPIO.output(spi_clk, False)
    GPIO.output(spi_clk, True)
    GPIO.output(spi_clk, False)
    GPIO.output(spi_clk, True)
    GPIO.output(spi_clk, False)

    value = 0
    for i in range(12):
        value <<= 1
        GPIO.output(spi_clk, True)
        if (GPIO.input(spi_miso)):
            value |= 0x1
        GPIO.output(spi_clk, False)

    GPIO.output(spi_ss, True)
    value = 20.0 + (value - 700) / 8.0
    sys.stdout.write(str(value))

    sys.stdout.write("\n")

    print 'Temp={0:0.1f}*C'.format(value)
    pubnub.publish('tempeon', {
        'columns': [
            ['x', time.time()],
            ['temperature_celcius', value]
            ]
	    })

                        '''print 0'''
                        global status
                        status = 0
                else:
                        '''print 1'''
                        global status
                        status = 1

                print status
                photoData={
                    "device_id" : "ref",
                    "device_type" : "refrigerator",
                    "channel" : "ch1",
                    "date" : "2016-04-12",
                    "value" : status }
                
                req = urllib2.Request('http://10.0.0.228:4001/devices')
                req.add_header('Content-Type', 'application/json')
                if count%300==0:
                        response=urllib2.urlopen(req,json.dumps(photoData))
                        #print 'response',response
                pubnub.subscribe(channels='my_channel', callback=callback, error=callback,connect=connect, reconnect=reconnect, disconnect=disconnect)

                pubnub.publish('my_channel', {
                    'columns': [
                        ['x', time.time()],
                        ['tv_operating_status', status]
                        ]

                    });      
Beispiel #26
0
from pubnub import Pubnub
import json
import time
import sys
from time import strftime
import base64
from PIL import Image

# Set up PubNub
pubnub = Pubnub(publish_key='pub-c-92b5e647-0c49-49a1-ab2a-4753777f53b9', subscribe_key='sub-c-02de9d80-9a93-11e5-9a49-02ee2ddab7fe',
                secret_key='sec-c-YTM5ZDM5ZmMtOTRmMS00Yzg2LThhYzQtYWI0Zjk2Yzg5M2U3')
channel = 'snapshots'

def _error(message):
	print(message)
	
# Open the most recent Motion snapshot
snapshot = Image.open("/var/lib/motion/lastsnap.jpg")
# Resize and save
snapshot = snapshot.resize((320,240),Image.ANTIALIAS)
snapshot.save("/home/Project/scaled.jpg",optimize=True,quality=85)

# Open the new scaled image and encode using base64
with open("/home/Project/scaled.jpg", "rb") as image_file:
    encoded_string = base64.b64encode(image_file.read())

# Send the encoded image alongside the episode id
pubnub.publish(
    channel = channel,
    message = {"picture" : encoded_string, "epid" : sys.argv[1]}, 
	error=_error)
Beispiel #27
0
#!/usr/bin/python3
import Adafruit_DHT
from pubnub import Pubnub
import time

pubnub = Pubnub(publish_key='demo', subscribe_key='demo')

while True:

    humidity, temp_C = Adafruit_DHT.read_retry(11, 4)
    temp_F = ((9/5)*temp_C) + 32

    pubnub.publish('temperature', {'eon': {'temperature_f': temp_F, 'temperature_c': temp_C}})
    pubnub.publish('humidity', {'eon': {'humidity': humidity}})
    time.sleep(5)
Beispiel #28
0
	def PublishImageData(self, file):
		pubnub_data = self.GetPubnubObject(file)
		message = {'CV_Data': pubnub_data}
		pubnub = Pubnub(publish_key="pub-c-93c6c384-e1a0-412f-87cf-e626aaab6a00", subscribe_key="sub-c-8ec9d89e-e4aa-11e5-a4f2-0619f8945a4f", auth_key="40ed6434-1991-4f7a-8034-20a072abde43")
		pubnub.publish("anubhav", message) 	
Beispiel #29
0

def disconnect(message):
  print("DISCONNECTED")

pubnub.subscribe(
  channels='kyberd',
  callback=callback,
  error=callback,
  #connect=connect,
  #reconnect=reconnect,
  #disconnect=disconnect
)

#pubnub.publish(channel='kyberd', message='Erm...', callback=callback, error=callback)
pubnub.publish(channel='kyberd', message='Hello from the PubNub Python SDK')






ob = {
  'weather': {
    'ttl': None
  },
  'inverter': {
    'ttl': None
  }
}
import paho.mqtt.client as mqtt
Beispiel #30
0
radio.enableDynamicPayloads()
radio.setRetries(5, 15)
radio.printDetails()
radio.openWritingPipe(RFUtil.PIPES[0])
radio.openReadingPipe(1, RFUtil.PIPES[1])

# Update information display
message = PubnubMessage(RFUtil.CMD_UPDATE_INFORMATION, "Information 1",
                        CURRENT_AVAILABLE, None)
radio.openWritingPipe(RFUtil.PIPES[2])
_send_payload_process(message)
radio.openWritingPipe(RFUtil.PIPES[0])

# Start Pubnub
try:
    pubnub.publish(PubnubMeta.CHANNEL_LOGGING, "Rise and Shine baby")
    pubnub.subscribe(channels=PubnubMeta.CHANNEL_CONTROL,
                     callback=_pubnub_callback,
                     error=_pubnub_error,
                     connect=_pubnub_connect,
                     reconnect=_pubnub_reconnect,
                     disconnect=_pubnub_disconnect)
    while True:
        while REQUEST_STATUS:
            POLLING_STATUS = False
            time.sleep(0.1)
        POLLING_STATUS = True
        print("####################")
        for sensor_name, lot in PARKING_LOT_DICTIONARY.items():
            message = PubnubMessage(RFUtil.CMD_LOT_STATUS, sensor_name, None,
                                    None)
	for line in ifile:
		if not line.strip():
			break
		if not ".wav" in line:
			break
		#For each result pass the type to eventMessage.py
		subprocess.Popen(['python','/home/Project/eventMessage.py', (line.rsplit(None, 1)[-1]), sys.argv[2], str(epid)], stdout=FNULL, stderr=subprocess.STDOUT)
		#Add to list of results
		episode.append(line.rsplit(None, 1)[-1])

# Find the most common type, as this will probably be the main cause of the audio event
data = Counter(episode)
print(data.most_common(1)[0][0])

# Call pictureMessage.py to send the snapshot
subprocess.Popen(['python','/home/Project/pictureMessage.py', str(epid)], stdout=FNULL, stderr=subprocess.STDOUT)

#Initialise PubNub
pubnub = Pubnub(publish_key='pub-c-92b5e647-0c49-49a1-ab2a-4753777f53b9', subscribe_key='sub-c-02de9d80-9a93-11e5-9a49-02ee2ddab7fe',
                secret_key='sec-c-YTM5ZDM5ZmMtOTRmMS00Yzg2LThhYzQtYWI0Zjk2Yzg5M2U3')
channel = 'episodes'
# Organise the episode message details
episodemessage = json.dumps({'level': 0, 'count' : episode, 'start': sys.argv[2], 'end' : sys.argv[3], 'epid' : str(epid)})
# Send via PubNub
pubnub.publish(
    channel = channel,
    message = episodemessage)
# Call PushPythonscript.py to send a Push Notification to the mobile with the common audio type
subprocess.Popen(['python','/home/Project/PushPythonscript.py', (data.most_common(1)[0][0]), sys.argv[2], str(epid)], stdout=FNULL, stderr=subprocess.STDOUT)

Beispiel #32
0
class AppWindow(QtGui.QMainWindow, remote.Ui_MainWindow):
    resSlot = QtCore.pyqtSignal(str, str)

    def __init__(self, parent=None, **kwargs):
        super(AppWindow, self).__init__(parent)
        self.setupUi(self)
        self.I = kwargs.get('I', None)
        self.setWindowTitle(self.I.H.version_string + ' : ' +
                            params.get('name', '').replace('\n', ' '))
        self.pubEdit.setText("pub-c-22260663-a169-4935-9c74-22925f4398af")
        self.subEdit.setText("sub-c-3431f4ba-2984-11e6-a01f-0619f8945a4f")
        self.channelLabel.setText(self.I.hexid)
        self.resetKeys()  #Connect to pubnub

        self.resSlot.connect(self.writeResults)
        self.thingSpeakCommand = None

        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.uploadToThingSpeak)
        self.uploadToThingSpeak()
        self.timer.start(15 * 1e3)  #15 seconds

        import inspect

        funcs = dir(self.I)
        self.methods = {}
        self.function_list = []
        for a in funcs:
            fn = getattr(self.I, a)
            try:
                args = inspect.getargspec(fn).args
            except:
                args = []

            if len(args) > 0:
                if inspect.ismethod(fn):
                    self.methods[a] = (
                        fn, args
                    )  #list of tuples of all methods in device handler
                    if args[0] == 'self':
                        self.function_list.append([a, args[1:]])

    def uploadToThingSpeak(self):
        if self.thingSpeakCommand:
            try:
                result = self.thingSpeakCommand[0](*self.thingSpeakCommand[1])
                params = urllib.urlencode({
                    'field1': float(result),
                    'key': str(self.thingSpeakKey.text())
                })
                headers = {
                    "Content-type": "application/x-www-form-urlencoded",
                    "Accept": "text/plain"
                }
                conn = httplib.HTTPConnection("api.thingspeak.com:80")
                conn.request("POST", "/update", params, headers)
                response = conn.getresponse()
                self.results_2.append('%s : %s' %
                                      (response.status, response.reason))
                data = response.read()
                conn.close()
            except Exception as e:
                self.results_2.append('Error : %s' % (e.message))
                pass

    def setThingSpeakCommand(self):
        try:
            message = str(self.cmdEditThingSpeak.text())
            fn_name = message.split('(')[0]
            args = message[message.find("(") +
                           1:message.find(")")].strip().split(',')
            total_args = []
            for t in args:
                if not len(t): continue
                if t[0] == "'" or t[0] == '"': total_args.append(t[1:-1])
                else: total_args.append(string.atoi(t))

            method = self.methods.get(fn_name)[0]
            if method == None:
                print('no such command :', fn_name)
                return 'no such command : %s' % fn_name
            else:
                #while self.hw_lock and self.active: pass
                #self.hw_lock=True
                self.thingSpeakCommand = [method, total_args]
        except Exception as e:
            self.results_2.append('Set Error : %s' % (e.message))
            pass

    def setListenState(self, state):
        if state:  #Enable listen
            try:
                self.pubnub.subscribe(self.I.hexid,
                                      callback=self.callback,
                                      error=self._error,
                                      connect=self._connect,
                                      reconnect=self._reconnect,
                                      disconnect=self._disconnect)
            except Exception as e:
                self.responseLabel.setText(e)
        else:
            self.pubnub.unsubscribe(self.I.hexid)

    def resetKeys(self):
        try:
            from pubnub import Pubnub
            self.pubnub = Pubnub(publish_key=str(self.pubEdit.text()),
                                 subscribe_key=str(self.subEdit.text()))
        except Exception as e:
            self.responseLabel.setText(e)

    def callback(self, full_message, channel):
        msg_type = full_message[0]
        senderId = str(full_message)[1:19]
        message = str(full_message)[19:]
        try:
            if msg_type == 'Q':  #Query
                self.resSlot.emit(message, 'in')
                fn_name = message.split('(')[0]
                args = message[message.find("(") +
                               1:message.find(")")].strip().split(',')
                total_args = []
                for t in args:
                    if not len(t): continue
                    if t[0] == "'" or t[0] == '"': total_args.append(t[1:-1])
                    else: total_args.append(string.atoi(t))

                method = self.methods.get(fn_name)[0]
                if method == None:
                    print('no such command :', fn_name)
                    return 'no such command : %s' % fn_name
                else:
                    #while self.hw_lock and self.active: pass
                    #self.hw_lock=True
                    result = method(*total_args)
                    #self.hw_lock=False
                    jsonres = json.dumps(result, cls=NumpyEncoder)
                    self.pubnub.publish(
                        channel=senderId, message='R' + self.I.hexid +
                        jsonres)  #R stands for response . Q for Query
                    self.resSlot.emit(
                        '%s %s %s %d %s... %s' %
                        (method.__name__, str(total_args), str(type(jsonres)),
                         len(jsonres), str(
                             jsonres[:20]), self.I.hexid + 'response'), 'out')
            elif msg_type == 'R':
                self.resSlot.emit(senderId + ' > ' + message, 'reply')

        except Exception as e:
            self.responseLabel.setText(e.message)

    def writeResults(self, txt, t):
        if t == 'in':
            self.results.append(
                'RECV:<span style="background-color: #FFFF00">' + txt +
                '</span')
        elif t == 'out':
            self.results.append(
                'SEND:<span style="background-color: #00FF00">' + txt +
                '</span')
        elif t == 'reply':
            self.results.append(
                'GOT :<span style="background-color: #00FFFF">' + txt +
                '</span')
        elif t == 'msg':
            self.results.append(
                'MSG :<span style="background-color: #000;color:#FFF">' + txt +
                '</span')

    def execRemote(self):
        chan = hex(0x1000000000000000 | int(str(self.sendID.text()), 16))
        msg = str(self.cmdEdit.text())
        self.pubnub.publish(channel=chan, message='Q' + self.I.hexid + msg)
        self.resSlot.emit('[' + chan + ']: ' + msg, 'out')

    def _connect(self, m):
        self.resSlot.emit("Connected to PubNub! Listening on " + m, 'msg')

    def _reconnect(self, m):
        self.resSlot.emit("Reconnected to PubNub!", 'msg')

    def _disconnect(self, m):
        self.resSlot.emit("Disconnected from PubNub!", 'msg')

    def _error(self, m):
        self.resSlot.emit(" PubNub Error!", 'msg')

    def __del__(self):
        try:
            self.pubnub.unsubscribe(self.I.hexid)
        except:
            pass
        try:
            self.pubnub.unsubscribe(self.I.hexid + 'response')
        except:
            pass

    def closeEvent(self, event):
        try:
            self.pubnub.unsubscribe(self.I.hexid)
        except:
            pass
        try:
            self.pubnub.unsubscribe(self.I.hexid + 'response')
        except:
            pass

        self.finished = True
Beispiel #33
0
####
#### Send the episode details via PubNub
####

from pubnub import Pubnub
import json
import time
import sys
from time import strftime

# Initialise PubNub
pubnub = Pubnub(publish_key='pub-c-92b5e647-0c49-49a1-ab2a-4753777f53b9', subscribe_key='sub-c-02de9d80-9a93-11e5-9a49-02ee2ddab7fe',
                secret_key='sec-c-YTM5ZDM5ZmMtOTRmMS00Yzg2LThhYzQtYWI0Zjk2Yzg5M2U3')
channel = 'episodes'

# Organise message details 
Videomessage = json.dumps({'level': 0, 'duration': sys.argv[1], 'start' : (strftime("%Y-%m-%d %H:%M"))})

# Send via PubNub
pubnub.publish(
    channel = channel,
    message = Videomessage)
Beispiel #34
0
class Server(Thread):
	def __init__(self, url, keepAlive = False, sendReceipts = False):
		super(Server, self).__init__()
		self.sendReceipts = sendReceipts
		self.keepAlive = keepAlive
		self.db = create_engine(url, echo=False, pool_size=10, pool_timeout=600,pool_recycle=300)

		self.Session = sessionmaker(bind=self.db)
		self.s = self.Session()
		self.job = None

		self.pubnub = Pubnub(os.environ['PUB_KEY'], os.environ['SUB_KEY'], None, False)

		self.timeout = int(os.getenv('TIMEOUT', 3600))
		# connectionManager = YowsupConnectionManager(self.timeout)
		connectionManager = YowsupConnectionManager()

		connectionManager.setAutoPong(keepAlive)		

		self.signalsInterface = connectionManager.getSignalsInterface()
		self.methodsInterface = connectionManager.getMethodsInterface()
		
		self.signalsInterface.registerListener("message_received", self.onMessageReceived)
		self.signalsInterface.registerListener("group_messageReceived", self.onGroupMessageReceived)
		self.signalsInterface.registerListener("image_received", self.onImageReceived)
		self.signalsInterface.registerListener("video_received", self.onVideoReceived)
		self.signalsInterface.registerListener("audio_received", self.onAudioReceived)
		self.signalsInterface.registerListener("vcard_received", self.onVCardReceived)
		self.signalsInterface.registerListener("location_received", self.onLocationReceived)
		self.signalsInterface.registerListener("receipt_messageSent", self.onReceiptMessageSent)
		self.signalsInterface.registerListener("receipt_messageDelivered", self.onReceiptMessageDelivered)		
		
		self.signalsInterface.registerListener("auth_success", self.onAuthSuccess)
		self.signalsInterface.registerListener("auth_fail", self.onAuthFailed)
		self.signalsInterface.registerListener("disconnected", self.onDisconnected)

		self.signalsInterface.registerListener("contact_gotProfilePicture", self.onGotProfilePicture)
		self.signalsInterface.registerListener("profile_setStatusSuccess", self.onSetStatusSuccess)
		self.signalsInterface.registerListener("group_createSuccess", self.onGroupCreateSuccess)
		self.signalsInterface.registerListener("group_createFail", self.onGroupCreateFail)
		self.signalsInterface.registerListener("group_gotInfo", self.onGroupGotInfo)
		self.signalsInterface.registerListener("group_addParticipantsSuccess", self.onGroupAddParticipantsSuccess)
		self.signalsInterface.registerListener("group_removeParticipantsSuccess", self.onGroupRemoveParticipantsSuccess)
		self.signalsInterface.registerListener("group_imageReceived", self.onGroupImageReceived)


		self.signalsInterface.registerListener("group_subjectReceived", self.onGroupSubjectReceived)
		self.signalsInterface.registerListener("notification_removedFromGroup", self.onNotificationRemovedFromGroup)
		self.signalsInterface.registerListener("notification_groupParticipantAdded", self.onNotificationGroupParticipantAdded)
		self.signalsInterface.registerListener("group_gotParticipants", self.onGotGroupParticipants)

		self.signalsInterface.registerListener("media_uploadRequestSuccess", self.onUploadRequestSuccess)
		# self.signalsInterface.registerListener("media_uploadRequestFailed", self.onUploadRequestFailed)
		self.signalsInterface.registerListener("media_uploadRequestDuplicate", self.onUploadRequestDuplicate)
		self.signalsInterface.registerListener("presence_available", self.onPresenceAvailable)
		self.signalsInterface.registerListener("presence_unavailable", self.onPresenceUnavailable)
		
		self.cm = connectionManager
		self.url = os.environ['URL']

		self.post_headers = {'Content-type': 'application/json', 'Accept': 'application/json'}		
		self.done = False

	def onUploadFailed(self, hash):
		print "Upload failed"
	
	def login(self, username, password, id):		
		self.username = username
		self.password = password
		self.account_id = id
		self.use_realtime = os.environ['USE_REALTIME'] == "true"
		self.pubnub_channel = os.environ['PUB_CHANNEL'] + "_%s" %self.username
		
		self._d("Logging in")
		self.methodsInterface.call("auth_login", (self.username, self.password))
		self.methodsInterface.call("presence_sendAvailable", ())
		
	def run(self):
		while not self.done:
			self.seekJobs()
			time.sleep(2)

	def _formatContacts(self, raw):
		contacts = raw.split(",")
		for i, _ in enumerate(contacts):		
			contacts[i] = contacts[i] + "@s.whatsapp.net"
		return contacts

	def _formatContact(self, phone_number):
		return phone_number + "@s.whatsapp.net"
	
	def seekJobs(self):
		jobs = self.s.query(Job).filter_by(sent=False, account_id=self.account_id, pending=False).all()
		if len(jobs) > 0:
			self._d("Pending Jobs %s" % len(jobs))

		acc = self._getAccount()
		self._d("Offline : %s" %acc.off_line, True)
		
		for job in jobs:									
			if self._onSchedule(job.scheduled_time) and acc.off_line == False:
				self._d("Calling %s" %job.method)
				job.runs += 1

				if job.off_line == True:
					account = self._getAccount()
					account.off_line = True										

					job.sent = True					
					self.job = job
					
					self.s.commit()
					self.cm.disconnect("Disconnecting for offline jobs")						
				else:
					if job.method == "group_create":
						res = self.methodsInterface.call(job.method, (job.args,))
						job.sent = True
					elif job.method == "group_end":
						res = self.methodsInterface.call(job.method, (job.args,))
						job.sent = True
					elif job.method == "group_addParticipants":
						self.methodsInterface.call(job.method, (job.targets, self._formatContacts(job.args),))
						job.sent = True
					elif job.method == "group_removeParticipants":
						# params = job.args.split(",")
						self.methodsInterface.call(job.method, (job.targets, self._formatContacts(job.args),))
						job.sent = True
					elif job.method == "group_getParticipants":				
						self.methodsInterface.call('group_getParticipants', (job.targets,))
						job.sent = True
					elif job.method == "contact_getProfilePicture":
						self.methodsInterface.call("contact_getProfilePicture", (job.args,))
						job.sent = True
					elif job.method == "sendMessage":
						
						if job.simulate == True:
							self.methodsInterface.call("typing_send", (job.targets,))
							self.methodsInterface.call("typing_paused", (job.targets,))

						job.whatsapp_message_id = self.sendMessage(job.targets, job.args)
						job.sent = True
					elif job.method == "broadcast_Text":
						jids = job.targets.split(",")
						targets = []
						for jid in jids:
							targets.append("*****@*****.**" %jid)
						job.whatsapp_message_id = self.methodsInterface.call("message_broadcast", (targets, job.args, ))

						job.sent = True
					elif job.method == "uploadMedia":
						asset = self.s.query(Asset).get(job.asset_id)

						if asset.mms_url == None:
							self.requestMediaUrl(asset)
						else:
							# find the jobs after this
							next_job = self.s.query(Job).filter_by(id=job.next_job_id, pending=True).first()
							next_job.pending = False
						job.sent = True					
					elif job.method == "sendImage":
						asset = self._getAsset(job.args)		
						targets = job.targets
						if "@" not in targets:
							targets = targets + "@s.whatsapp.net"
						job.whatsapp_message_id = self.sendImage(targets, asset)
						job.sent = True
					elif job.method == "sendVideo":
						asset = self.s.query(Asset).get(job.asset_id)
						job.whatsapp_message_id = self.sendVideo(job.targets, asset)
						job.sent = True
					elif job.method == "sendContact":
						jids = job.targets.split(",")
						for jid in jids:
							self.sendVCard(jid, job.args)
						job.sent = True
					elif job.method == "sendAudio":
						asset = self.s.query(Asset).get(job.asset_id)
						self.sendAudio(job.targets + "@s.whatsapp.net", asset)
						job.sent = True
					elif job.method == "broadcast_Video":
						args = job.args.split(",")
						asset = self._getAsset(job.args)
						jids = job.targets.split(",")
						for jid in jids:
							self.sendVideo(jid + "@s.whatsapp.net", asset)
							time.sleep(1)
						job.sent = True
					elif job.method == "broadcast_Group_Image":
						asset = self._getAsset(job.args)
						self.sendImage(job.targets, asset)
						job.sent = True
					elif job.method == "broadcast_Group_Video":
						asset = self._getAsset(job.args)
						self.sendVideo(job.targets, asset)
						job.sent = True
					elif job.method == "sendLocation":
						location = self.s.query(Location).get(job.args)
						self.sendLocation(job.targets, location)
						job.sent = True					
					elif job.method == "syncGroup":
						self._d("Calling group_getInfo %s" %job.args)
						self.methodsInterface.call("group_getInfo", (job.args,))
						job.sent = True
		if acc.off_line == True and self.job == None:
			self._d("Reconnecting")
			
			acc = self._getAccount()						
			acc.off_line = False
			self.s.commit()

			self.methodsInterface.call("auth_login", (self.username, self.password))
			self.methodsInterface.call("presence_sendAvailable", ())
			

		self.s.commit()		

	def _d(self, message, debug=False):
		if debug == False:
			logging.info("%s - %s" %(self.username, message))
		else:
			logging.debug("%s - %s" %(self.username, message))

	def _onSchedule(self,scheduled_time):
		return (scheduled_time is None or datetime.now() > self.utc_to_local(scheduled_time))

	def _getContact(self,phone_number):
		return self.s.query(Contact).filter_by(account_id = self.account_id, phone_number = phone_number).scalar()

	def _getAccount(self):
		return self.s.query(Account).get(self.account_id)

	def _getAsset(self, args):
		args = args.split(",")
		asset_id = args[0]
		return self.s.query(Asset).get(asset_id)

	def _messageExists(self, whatsapp_message_id):
		message = self.s.query(Message).filter_by(whatsapp_message_id=whatsapp_message_id).scalar()
		return message is not None

	def _sendRealtime(self, message):
		if self.use_realtime:
			self.pubnub.publish({
				'channel' : self.pubnub_channel,
				'account' : self.username,
				'message' : message
			})

	def onReceiptMessageDelivered(self, jid, messageId):
		self._d("Delivered %s" %messageId)
		self._d("From %s" %jid)
		# self.s.query(Job).filter_by(sent=False).all()

		session = self.Session()
		job = session.query(Job).filter_by(sent=True, whatsapp_message_id=messageId).scalar()
		if job is not None:
			job.received = True
			session.commit()

			if job.method == "sendMessage" or job.method == "sendImage":
				m = session.query(Message).get(job.message_id)
				self._d("Looking for message with id to send a receipt %s" %job.message_id)
				if m is not None:
					m.received = True
					m.receipt_timestamp = datetime.now()
					session.commit()
					
					data = { "receipt" : { "message_id" : m.id } }
					self._post("/receipt", data)

					self._sendRealtime({
						'type' : 'receipt',
						'message_id': m.id
					})
			else:
				data = { "receipt" : { "message_id" : messageId, "phone_number" : jid.split("@")[0] } }
				self._post("/broadcast_receipt", data)				

				

	def onReceiptMessageSent(self, jid, messageId):
		self._d("Sent %s" %messageId)
		self._d("To %s" %jid)

	def onPresenceAvailable(self, jid):
		self._d("JID available %s" %jid)
		phone_number = jid.split("@")[0]
		contact = self._getContact(phone_number)

		if contact is not None:
			url = "/contacts/%s" %contact.id
			self._patch(url, { "contact" : { "last_seen" : str(datetime.now()) } })

	def onPresenceUnavailable(self, jid):
		self._d("JID unavilable %s" %jid)
		self._d("Last seen is %s" %last)

		# TODO: removed last seen variable
		# if last == "deny":
		# 	self._d("this number %s has blocked you" %jid)


	def onUploadRequestDuplicate(self,_hash, url):
		self._d("Upload duplicate")
		self._d("The url is %s" %url)
		self._d("The hash is %s" %_hash)	

		asset = self.s.query(Asset).filter_by(asset_hash=_hash).order_by(desc(Asset.id)).first()
		self._d("Asset id %s" %asset.mms_url)
		asset.mms_url = url
		self.s.commit()

		self._sendAsset(asset.id)

		put_url = "/assets/%s" %asset.id		
		data = { "asset" : { "mms_url": url } }
		self._patch(put_url, data)		

	def utc_to_local(self,utc_dt):
		# get integer timestamp to avoid precision lost
		timestamp = calendar.timegm(utc_dt.timetuple())
		local_dt = datetime.fromtimestamp(timestamp)
		assert utc_dt.resolution >= timedelta(microseconds=1)
		return local_dt.replace(microsecond=utc_dt.microsecond)

	def onUploadRequestSuccess(self, _hash, url, removeFrom):
		self._d("Upload Request success")
		self._d("The url is %s" %url)
		self._d("The hash is %s" %_hash)
		asset = self.s.query(Asset).filter_by(asset_hash=_hash).order_by(desc(Asset.id)).first()
		asset.mms_url = url
		self.s.commit()

		path = self.getImageFile(asset)

		self._d("To upload %s" %path)
		self._d("To %s" %self.username)

		MU = MediaUploader(self.username + "@s.whatsapp.net", self.username + "@s.whatsapp.net", self.onUploadSucccess, self.onUploadError, self.onUploadProgress)
		
		self._d("Path %s" %path)
		self._d("Url %s" %url)
		
		MU.upload(path, url, asset.id)

	def _sendAsset(self, asset_id):
		self._d("Sending an uploaded asset %s" %asset_id)
		upload_jobs = self.s.query(Job).filter_by(asset_id = asset_id, method="uploadMedia", sent=True).all()
		self._d("Found %s jobs tied to this asset" %len(upload_jobs))
		for job in upload_jobs:
			self._d("Found job with sent %s" %job.sent)			
			self._d("Found job %s - %s " %(job.id, job.next_job_id))
			if job.next_job_id is not None:
				next_job = self.s.query(Job).get(job.next_job_id)
				if next_job.pending == True and next_job.sent == False:
					next_job.pending = False

		self.s.commit()

	def onUploadSucccess(self, url, _id):
		self._d("Upload success!")
		self._d("Url %s" %url)
		if _id is not None:
			asset = self.s.query(Asset).get(_id)
			asset.mms_url = url

			self.s.commit()
			self._sendAsset(asset.id)
		
	def onUploadError(self):
		self._d("Error with upload")

	def onUploadProgress(self, progress):
		self._d("Upload Progress")

	def _link(self, url):
		if url is not None and not url.startswith("http"):
			return os.environ['URL'] + url
		else:
			return url

	def requestMediaUrl(self, asset):
		self._d("About to request for Asset %s" %asset.id)
		self._d("Requesting Url: %s" %asset.url)	
		mtype = asset.asset_type.lower()
		sha1 = hashlib.sha256()

		url = self._link(asset.url)
		preview = self._link(asset.preview_url)
		self._d("Full url : %s" %url)
		self._d("Preview url: %s" %preview)

		
		file_name = self.getImageFile(asset)

		self._d("File name: %s" %file_name)

		fp = open(file_name,'wb')
		fp.write(requests.get(url).content)
		fp.close()

		self._d("Written file to %s" %file_name)

		if asset.asset_type != "Audio":
			tb_path = self.getImageThumbnailFile(asset)			
			tb = open(tb_path, 'wb')
			self._d("Preview URL %s" %preview)
			tb.write(requests.get(preview).content)
			tb.close()
			self._d("Written thumbnail path : %s" %tb_path)


		fp = open(file_name, 'rb')
		try:
			sha1.update(fp.read())
			hsh = base64.b64encode(sha1.digest())

			asset.asset_hash = hsh
			self.s.commit()

			rst = self.methodsInterface.call("media_requestUpload", (hsh, mtype, os.path.getsize(file_name)))
			self._d("Requested media upload for %s" %asset.id)
		finally:
			fp.close()  

	def getImageFile(self, asset):
		if asset.asset_type == "Image":
			path = "_%s"%asset.id + asset.name
			file_name = "tmp/%s" %path
			return file_name
		elif asset.asset_type == "Video":
			path = "_%s"%asset.id + asset.name
			file_name = "tmp/%s.mp4" %path
			self._d("Image filename %s" %file_name)
			return file_name
		elif asset.asset_type == "Audio":
			path = "_%s"%asset.id + asset.name
			file_name = "tmp/%s" %path
			return file_name

	def getImageThumbnailFile(self, asset):
		if asset.asset_type == "Image":
			path = "_%s"%asset.id + "_thumb_" + asset.name
			file_name = "tmp/%s" %path
			return file_name		
		else:
			path = "_%s"%asset.id + "_thumb_" + asset.name
			file_name = "tmp/%s.jpg" %path
			return file_name	

	def sendVideo(self, target, asset):
		self._d("In sendVideo %s" %asset.id)
		thumbnail = self.getImageThumbnailFile(asset)
		self._d("The thumbnail %s" %thumbnail)
		
		f = open(thumbnail, 'r')
		stream = base64.b64encode(f.read())
		f.close()		
		rst = self.methodsInterface.call("message_videoSend",(target,asset.mms_url,"Video", str(os.path.getsize(self.getImageThumbnailFile(asset))), stream))
		self._d("Called video send %s" %rst)
		return rst

	def sendVCard(self, target, args):
		account = self.s.query(Account).get(self.account_id)

		card = vobject.vCard()
		params = args.split(",")
		family_name = params[0]
		given_name = params[1]
		name = family_name + " " + given_name

		card.add('fn')
		card.fn.value = name

		card.add('n')
		card.n.value = vobject.vcard.Name(family=family_name, given=given_name)

		self._d("First name %s" %family_name)
		self._d("Last name %s" %given_name)

		api_url = self.url  + "/api/v1/base/status?token=%s" %account.auth_token
		headers = {'Content-type': 'application/json', 'Accept': 'application/json'}
		r = requests.get(api_url, headers=headers)
		response = r.json()

		
		del params[0]
		del params[0]		

		for number in params:
			tel = number.split(":")
			num = card.add('tel')
			num.value = tel[1]
			num.type_param = tel[0]

		self._d("Response is %s" %response)
		if response['profile_pic'] != self.url + '/blank-profile.png':			
			tb = open('tmp/profile_thumb.jpg', 'wb')
			tb.write(requests.get(response['profile_pic']).content)
			tb.close()

			f = open('tmp/profile_thumb.jpg', 'r')
			stream = base64.b64encode(f.read())
			f.close()

			card.add('photo')
			card.photo.value = stream
			card.photo.type_param = "JPEG"
			# card.photo.encoding_param = "b"


		self._d("Data %s" %card.serialize())
		self.methodsInterface.call("message_vcardSend", (target, card.serialize(), name))

	def sendAudio(self, target, asset):
		self._d("Sending %s" %asset.mms_url)
		self._d("To %s" %target)
		self._d("Name %s" %asset.name)
		self._d("Size %s" %asset.audio_file_size)
		rst = self.methodsInterface.call("message_audioSend", (target, asset.mms_url, asset.name, str(asset.audio_file_size)))
		return rst

	def sendImage(self, target, asset):
		f = open(self.getImageThumbnailFile(asset), 'r')
		stream = base64.b64encode(f.read())
		f.close()    	
		self._d("Target %s" %target)
		self._d("URL %s" %asset.mms_url)
		self._d("URL %s" %asset.asset_hash)
		rst = self.methodsInterface.call("message_imageSend",(target,asset.mms_url,"Image", str(os.path.getsize(self.getImageThumbnailFile(asset))), stream))
		self._d("Result of send image %s" %rst)
		return rst

	def sendMessage(self, target, text):
		self._d("Message %s" %text)
		jid = target
		self._d("To %s" %jid)
		rst = self.methodsInterface.call("message_send", (jid, text))	
		return rst

	def sendLocation(self, target, location):
		self._d("Sending location %s,%s to %s" %(str(location.latitude), str(location.longitude), target))
		jid = self._formatContact(target)
		# message_locationSend(str jid,float latitude,float longitude,str preview)

		rst = self.methodsInterface.call("message_locationSend", (jid, str(location.latitude), str(location.longitude), location.preview))
		return rst


	def onGroupSubjectReceived(self,messageId,jid,author,subject,timestamp,receiptRequested):
		self._d("Group subject received")
		if receiptRequested and self.sendReceipts:
			self.methodsInterface.call("message_ack", (jid, messageId))

		data = { "name" : subject, "group_type" : "External", "jid" : jid }
		self._post("/groups", data)
		self._d("Updated the group")

	def onGroupAddParticipantsSuccess(self, groupJid, jid):
		self._d("Added participant %s" %jid)
		# check the profile pic
		self.checkProfilePic(jid[0])
		self._post("/update_membership", { "groupJid" : groupJid, "type": "add", "contact" : jid.split("@")[0]})

	def onGroupRemoveParticipantsSuccess(self, groupJid, jid):
		self._d("Removed participant %s" %jid)

	def onNotificationGroupParticipantAdded(self, groupJid, jid):
		self._d("Group participant added %s" %jid)		
		data = { "groupJid" : groupJid, "phone_number": jid.split("@")[0] }
				
		self._post("/groups/add_member", data)

	def onNotificationRemovedFromGroup(self, groupJid,jid):
		self._d("You were removed from the group %s" %groupJid)

		put_url = self.url  + "/groups/remove_member"
		data = { "groupJid" : groupJid, 'phone_number': jid.split("@")[0] }		
		self._post("/groups/remove_member", data)
		self._d("Updated the group")

	def onGotGroupParticipants(self, groupJid, jids):
		self._d("Got group participants")

		data = { "groupJid" : groupJid, "jids" : jids }
		self._post("/groups/update_membership", data)

	def onGroupCreateSuccess(self, groupJid):
		self._d("Created with id %s" %groupJid)
		self.methodsInterface.call("group_getInfo", (groupJid,))

	def onGroupGotInfo(self,jid,owner,subject,subjectOwner,subjectTimestamp,creationTimestamp):
		self._d("Group info %s - %s" %(jid, subject))
		self._d("Group owner %s" %owner)
		self._d("Subject owner %s" %subjectOwner)
		
		data = { "name" : subject, "jid" : jid, "owner": owner, "subjectOwner" : subjectOwner }
		self._post("/update_group", data)
		self._d("Updated the group %s" %subject)

		create_job = self.s.query(Job).filter_by(method="group_create", args=subject).first()
		if create_job is not None and create_job.next_job_id is not None:
			next_job = self.s.query(Job).get(create_job.next_job_id)

			self._d("Next job %s" %next_job.id)
			self._d("Next job %s" %next_job.method)
			self._d("Next job sent? %s" %next_job.sent)
			self._d("Next job runs? %s" %next_job.runs)
			
			will_run = (next_job.method == "group_addParticipants" and next_job.sent == True and next_job.runs == 0)
			self._d("Will run? %s" %will_run)
			if next_job.method == "group_addParticipants" and next_job.sent == True and next_job.runs == 0:
				next_job.sent = False
				next_job.targets = jid
				self.s.commit()
			else:
				self._d("About to call get participants on %s" %jid)
				self.methodsInterface.call('group_getParticipants', (jid,))
		else:
			self._d("About to call get participants on %s" %jid)
			self.methodsInterface.call('group_getParticipants', (jid,))

	def onGroupCreateFail(self, errorCode):
		self._d("Error creating a group %s" %errorCode)

	def onSetStatusSuccess(self,jid,messageId):
		self._d("Set the profile message for %s - %s" %(jid, messageId))

	def onAuthSuccess(self, username):
		self._d("We are authenticated")
		self.methodsInterface.call("ready")
		self.setStatus(1, "Authenticated")
        
	def setStatus(self, status, message="Status message"):
		self._d("Setting status %s" %status)
		data = { "status" : status, "message" : message }
		self._post("/status", data)

	def onAuthFailed(self, username, err):
		self._d("Authentication failed for %s" %username)
		self._post("/wa_auth_error", {})

	def _postOffline(self, args):
		url = os.environ['API_URL']
		headers = {'Content-type': 'application/json', 'Accept': 'application/json'}
		params = { "nickname" : account.name, "password" : account.whatsapp_password, "jid" : account.phone_number }
		r = requests.post(url, data=dict(params.items() + args.items()))
		return r
		
	def onDisconnected(self, reason):
		self._d("Disconnected! Reason: %s" %reason)
		self.setStatus(0, "Got disconnected")
		
		account = self.s.query(Account).get(self.account_id)
		if account.off_line == False:
			self._d('About to log in again with %s and %s' %(self.username, self.password))
			self._d('Unscheduled outtage for this number')

			rollbar.report_message('Unscheduled outage for %s - %s' %(self.username, account.name), 'warning')
			self._d('Going to wait for a few minutes before trying to log in again')
			time.sleep(15)
			self.login(self.username, self.password, self.account_id)
		elif account.off_line == True and self.job is not None:			
			# call the current job
			job = self.job
			url = os.environ['API_URL']
			headers = {'Content-type': 'application/json', 'Accept': 'application/json'}
			if job.method == "profile_setStatus":				
				args = { "nickname" : account.name, "method" : job.method, "password" : account.whatsapp_password, "status" : job.args, "jid" : account.phone_number }
				r = requests.post(url, data=args)
				self._d(r.text)
			elif job.method == "setProfilePicture":				
				ret = self._postOffline({"method" : job.method, "image_url" : job.args })
				self._d(ret.text)
			elif job.method == "broadcast_Image":
				image_url = job.args.split(",")[1]
				full_url = os.environ['URL'] + image_url
				self._d(full_url)				
				args = { "nickname" : account.name, "targets" : job.targets, "method" : job.method , "password" : account.whatsapp_password , "image" : full_url, "jid" : account.phone_number, "externalId" : job.id }

				r = requests.post(url, data=args)
				self._d(r.text)

			self.job = None
			# account.off_line = False
			self.s.commit()


	def onGotProfilePicture(self, jid, imageId, filePath):
		self._d('Got profile picture')
		url = self.url + "/contacts/" + jid.split("@")[0] + "/upload?account=" + self.username
		files = {'file': open(filePath, 'rb')}
		r = requests.post(url, files=files)

	def checkProfilePic(self, jid):
		pull_pic = os.environ['PULL_STATUS_PIC']
		if pull_pic == "true":
			phone_number = jid.split("@")[0]
			get_url = self.url + "/profile?phone_number=" + phone_number + "&account=" + self.username
			headers = {'Content-type': 'application/json', 'Accept': 'application/json'}
			r = requests.get(get_url, headers=headers)
			response = r.json()
			
			if response['profile_url'] == '/missing.jpg':		
				self.methodsInterface.call("contact_getProfilePicture", (jid,))	

	def onGroupMessageReceived(self, messageId, jid, author, content, timestamp, wantsReceipt, pushName):
		self._d('Received a message on the group %s' %content)
		self._d('JID %s - %s - %s' %(jid, pushName, author))

		if wantsReceipt and self.sendReceipts:
			self.methodsInterface.call("message_ack", (jid, messageId))
		
		if self._messageExists(messageId) == False:
			data = { "message" : { "text" : content, "group_jid" : jid, "message_type" : "Text", "whatsapp_message_id" : messageId, "name" : pushName, "jid" : author }}
			self._post("/receive_broadcast", data)

			self.checkProfilePic(author)
			self._sendRealtime({
				'type' : 'text',
				'phone_number' : jid,
				'text' : content,
				'name' : pushName
			})
		else:
			rollbar.report_message('Duplicate group message (%s) %s - %s' %(messageId, self.username, account.name), 'warning')

	def _patch(self,url,data):
		data.update(account = self.username)
		headers = {'Content-type': 'application/json', 'Accept': 'application/json'}
		r = requests.patch(self.url + url, data=json.dumps(data), headers=headers)

	def _post(self, url, data):
		data.update(account = self.username)
		headers = {'Content-type': 'application/json', 'Accept': 'application/json'}
		r = requests.post(self.url + url, data=json.dumps(data), headers=headers)

	def onMessageReceived(self, messageId, jid, messageContent, timestamp, wantsReceipt, pushName, isBroadCast):
		self._d('Message Received %s' %messageContent)
		phone_number = jid.split("@")[0]

		if wantsReceipt and self.sendReceipts:
			self.methodsInterface.call("message_ack", (jid, messageId))
		
		if self._messageExists(messageId) == False:
			data = { "message" : { "text" : messageContent, "phone_number" : phone_number, "message_type" : "Text", "whatsapp_message_id" : messageId, "name" : pushName  }}
			self._post("/messages", data)

			self._sendRealtime({
				'type' : 'text',
				'phone_number' : phone_number,
				'text' : messageContent,
				'name' : pushName
			})
			
			self.checkProfilePic(jid)
		else:
			rollbar.report_message('Duplicate message (%s) %s - %s' %(messageId, self.username, account.name), 'warning')

	def onLocationReceived(self, messageId, jid, name, preview, latitude, longitude, wantsReceipt, isBroadcast):
		self._d('Location Received')	
		phone_number = jid.split("@")[0]

		if wantsReceipt and self.sendReceipts:
			self.methodsInterface.call("message_ack", (jid, messageId))

		data = { "location" : { 'latitude' : latitude, 'longitude': longitude, 'preview' : preview, 'phone_number' : phone_number, "whatsapp_message_id" : messageId, 'name' : name } }
		self._post("/locations", data)
		

	def onImageReceived(self, messageId, jid, preview, url, size, wantsReceipt, isBroadCast):	
		self._d('Image Received')	
		phone_number = jid.split("@")[0]

		data = { "message" : { 'url' : url, 'message_type' : 'Image' , 'phone_number' : phone_number, "whatsapp_message_id" : messageId, 'name' : '' } }
		self._post("/upload", data)

		if wantsReceipt and self.sendReceipts:
			self.methodsInterface.call("message_ack", (jid, messageId))

		self._sendRealtime({
			'type' : 'image',
			'phone_number' : phone_number,
			'url' : url,
			'name' : ''
		})

		self.checkProfilePic(jid)

	def onGroupImageReceived(self, messageId, jid, author, preview, url, size, wantsReceipt):
		phone_number = author.split("@")[0]
		self._d("Group image received %s - %s - %s - %s " %(messageId, jid, phone_number, url))

		if wantsReceipt and self.sendReceipts:
			self.methodsInterface.call("message_ack", (jid, messageId))

		data = { "message" : { 'url' : url, 'message_type' : 'Image', 'phone_number': phone_number , 'group_jid' : jid, "whatsapp_message_id" : messageId, 'name' : '' } }
		self._post("/upload", data)

		self._sendRealtime({
			'type' : 'image',
			'group_jid' : jid,
			'url' : url,
			'from' : phone_number
		})
	
	def onVCardReceived(self, messageId, jid, name, data, wantsReceipt, isBroadcast):				
		vcard = vobject.readOne( data )
		vcard.prettyPrint()

		data = { "vcard" : { 'phone_number' : jid.split("@")[0], 'whatsapp_message_id' : messageId, 'data' : vcard.serialize() }}		
		self._post("/vcards", data)

		if wantsReceipt and self.sendReceipts:
			self.methodsInterface.call("message_ack", (jid, messageId))

	def onAudioReceived(self, messageId, jid, url, size, wantsReceipt, isBroadcast):
		self._d("Audio received %s" %messageId)
		self._d("url: %s" %url)
		phone_number = jid.split("@")[0]

		data = { "message" : { 'url' : url,  'message_type': 'Audio', 'phone_number' : phone_number, "whatsapp_message_id" : messageId, 'name' : '' } }
		self._post("/upload", data)
		
		if wantsReceipt and self.sendReceipts:
			self.methodsInterface.call("message_ack", (jid, messageId))

	def onVideoReceived(self, messageId, jid, mediaPreview, mediaUrl, mediaSize, wantsReceipt, isBroadcast):
		self._d("Video Received %s" %messageId)
		self._d("From %s" %jid)
		self._d("url: %s" %mediaUrl)

		phone_number = jid.split("@")[0]
		data = { "message" : { 'url' : mediaUrl, 'message_type' : 'Video', 'phone_number' : phone_number, "whatsapp_message_id" : messageId, 'name' : '' } }
		self._post("/upload", data)

		# Send a receipt regardless of whether it was a successful upload
		if wantsReceipt and self.sendReceipts:
			self.methodsInterface.call("message_ack", (jid, messageId))
		# r = requests.post(post_url, data=json.dumps(data), headers=headers)

	def onGotProfilePicture(self, jid, imageId, filePath):
		self._d('Profile picture received')
		url = self.url + "/contacts/" + jid.split("@")[0] + "/upload?account=" + self.username
		files = {'file': open(filePath, 'rb')}
		r = requests.post(url, files=files)
Beispiel #35
0
class BaseAppiumTest(unittest.TestCase):
    
    driver = None
    screenshot_count = 0
    screenshot_dir = None
    desired_capabilities_cloud = {}
    ignoreBuddyTests = 0
    buddyCommandName = ""
    buddyName = ""
    buddyCheckFileName = ""
    buddyCheckComplete = False
    channel = "Trilleon-Automation"
    DBID = ""
    project_id = ""
    gridIdentity = ""
    buddyIdentity = ""
    pubnub = None
    jsonGridPrefix = ""
    jsonBuddyGridPrefix = ""
    heartbeat_index = 1
    last_heartbeat_detected = None
    max_time_since_heartbeat = 80
    partialDataDelimiter = "$$$"
    
    fatalErrorDetected = False
    fatalErrorMessage = ""
    
    ready = False
    started = False
    complete = False
    timeout_default = 300
    test_execution_timeout = 4800
    parsing_xml = False
    results = ""
    auto_screenshot_index = 0
    run_command = ""
    test_run_id_internal = ""

    def setUp(self, appium_url=None, platform_name=None, bundle_id = None, application_file=None, application_package=None, screenshot_dir=None,
                 application_activity=None, automation_name=None):
        global test_run_id
        test_run_id = str(uuid.uuid4())
        self.test_run_id_internal = test_run_id
        log("test_run_id [" + test_run_id + "]")
        with open("test_run_id.txt", "w") as f:
            f.write(test_run_id)

        self.pubnub = Pubnub(publish_key="TODO: YOUR KEY HERE!",subscribe_key="TODO: YOUR KEY HERE!")
        self.setChannelPrefixes()
        self.pubnub.subscribe(channels=self.channel, callback=callback, error=error)
        self.set_screenshot_dir('%s/screenshots' % (os.getcwd()))
        
        # Buddy test run information.
        self.buddyName = "Trilleon-Automation-" + os.environ.get('BUDDY')
        self.ignoreBuddyTests = os.environ.get('IGNOREBUDDYSYSTEM')
        self.buddyCommandName = "manual_set_buddy_" + os.environ.get('BUDDY_RELATIONSHIP')
        
        # Set Buddy Check-In file path.
        directoryPieces = os.getcwd().split("/")
        parentDirectory = ""
        index = len(directoryPieces)
        for piece in directoryPieces:
            index -= 1
            if index > 0:
                parentDirectory += piece + "/"
        self.buddyCheckFileName = parentDirectory + self.buddyName.replace(".", "").replace("-", "") + ".txt"
        
        # Set test run command.
        self.run_command = os.environ.get('RUN_COMMAND')
        with open("testresultsjson.txt", "w") as f:
            f.write("[")

        # Set up driver
        if os.environ['DEVICE_PLATFORM'] == "ios":
            self.desired_capabilities_cloud["showXcodeLog"] = True
            self.desired_capabilities_cloud["useNewWDA"] = False
            self.desired_capabilities_cloud["wdaLocalPort"] = os.environ['WDA_LOCAL_PORT']
            self.desired_capabilities_cloud["autoAcceptAlerts"] = True # iOS -- Dismisses device level popups automatically.
        else:
            self.desired_capabilities_cloud["systemPort"] = os.environ['UNIQUE_BOOT_PORT']
            self.desired_capabilities_cloud["autoGrantPermissions"] = True # Android 1.6.3+ -- Gives app permissions before starting.
        self.desired_capabilities_cloud["app"] = os.environ['APPLICATION']
        self.desired_capabilities_cloud["udid"] = os.environ['DEVICE_UDID']
        self.desired_capabilities_cloud["automationName"] = os.environ['DRIVER']
        self.desired_capabilities_cloud["platformName"] = os.environ['DEVICE_PLATFORM']
        if 'PLATFORM_VERSION' in os.environ:
            self.desired_capabilities_cloud["platformVersion"] = os.environ['PLATFORM_VERSION']
        self.desired_capabilities_cloud["deviceName"] = os.environ['DEVICE_UDID']
        self.desired_capabilities_cloud["newCommandTimeout"] = 99999
        self.desired_capabilities_cloud["launchTimeout"] = 99999
        time.sleep(5)
        #try:
        self.driver = webdriver.Remote("http://" + os.environ['HOST'] + ":" + os.environ['UNIQUE_PORT'] + "/wd/hub", self.desired_capabilities_cloud)
        #except Exception as e:
        #log("Error Instantiating Driver [" + str(e) + "]. Attempting to continue anyway.")
        time.sleep(10)

    def postMessage(self, message):
        postString = self.jsonGridPrefix + message
        self.pubnub.publish(self.channel, postString, callback=_callback, error=error)
        log("Request posted to PubNub [" + postString + "]")

    def setChannelPrefixes(self):
        global test_run_id
        log("PUBSUB CHANNEL ID: " + self.channel)
        self.gridIdentity = "Trilleon-Automation-" + os.environ['GRID_IDENTITY_PREFIX']
        self.jsonGridPrefix = "{\"test_run_id\":\"" + test_run_id + "\"},{\"grid_identity\":\"" + self.gridIdentity + "\"},{\"grid_source\":\"server\"},{\"grid_context\":\"StandardAlert\"},"
        self.jsonBuddyGridPrefix = "{\"test_run_id\":\"" + test_run_id + "\"},{\"grid_identity\":\"" + self.buddyName + "\"},{\"grid_source\":\"server\"},{\"grid_context\":\"BuddyMessage\"},"

    # Close down the driver, call XML and JSON finalizer, close PubNub connection, and handle any fatal execution error.
    def tearDown(self):
        self.pubnub.unsubscribe(self.channel)
        self.writeAutomationResults('TEST-all.xml')
        if self.fatalErrorDetected == True:
            with open("FatalErrorDetected.txt", "w") as f:
                f.write(self.fatalErrorMessage)
        time.sleep(5)
        try:
            self.driver.quit()
        except:
            log("Error encountered while quitting driver")

        with open("test_status.txt", "w") as f:
            f.write(os.environ['TEST_RUN_STATUS'])
        pylogtext = ""
        with open("PyLog.txt", "r") as f:
            pylogtext = f.read()
        if "CRITICAL_SERVER_FAILURE_IN_APPIUM_TEST" in pylogtext:
            raise Exception("CRITICAL_SERVER_FAILURE_IN_APPIUM_TEST Detected!")

    # Writes all XML to storage file, and verifies JSON validity so that HTML report is rendered correctly.
    def writeAutomationResults(self, filename):
        # Verify that JSON recorded is valid. Add placeholder JSON if it is not.
        text = ""
        with open("testresultsjson.txt", "r") as f:
            text = f.read() # Replace any missing commas between JSON objects and attributes.
        
        if len(self.results) > 0:
            if "failure" in self.results:
                os.environ['TEST_RUN_STATUS'] = "UNSTABLE"
            else:
                os.environ['TEST_RUN_STATUS'] = "SUCCESS"
            # Game error popup check.
            if self.fatalErrorDetected:
                os.environ['TEST_RUN_STATUS'] = "CRASH_DURING_RUN"
                with open("testresultsjson.txt", "a") as f:
                    f.write("{\"order_ran\":\"999\", \"status\":\"Failed\", \"name\":\"ERROR_POPUP\", \"class\":\"FATAL_ERROR\", \"test_categories\":\"ERROR_POPUP\", \"result_details\":\"The game produced an error popup that affected automation execution. Check screenshot for details.\", \"assertions\":[]},")
            with open(os.getcwd() + "/" + filename, "w") as f:
                f.write(self.results)

        else:
            # Failure occurred - likely an app crash. Send PubNub History to help investigate where it happened.
            log("FATAL APPLICATION ERROR DISRUPTED AUTOMATION")
            # If there is existing JSON, report that app crashed or hanged.
            if len(text) > 5:
                os.environ['TEST_RUN_STATUS'] = "CRASH_DURING_RUN"
                with open("testresultsjson.txt", "a") as f:
                    f.write("{\"order_ran\":\"999\", \"status\":\"Failed\", \"name\":\"GAME_CRASHED_OR_HANGED\", \"class\":\"FATAL_ERROR\", \"test_categories\":\"CRASH_HANG\", \"result_details\":\"The game either suddenly crashed, or automation execution encountered an unhandled fatal error that halted test execution. View screenshot for details.\", \"assertions\":[]},")
            else:
                # If results were not recorded, then the app never loaded, crashed, or automation could not launch.
                if "checking_in" not in self.get_communication_history():
                    os.environ['TEST_RUN_STATUS'] = "CRASH_DURING_LAUNCH"
                    with open("testresultsjson.txt", "w") as f:
                        f.write("[{\"order_ran\":\"0\", \"status\":\"Failed\", \"name\":\"GAME_LAUNCH_FAILURE\", \"class\":\"FATAL_ERROR\", \"test_categories\":\"LAUNCH_FAILURE\", \"result_details\":\"The game crashed on load, or otherwise failed to reach a state where automation could register on the pubsub communication channel.\", \"assertions\":[]},")
                else:
                    os.environ['TEST_RUN_STATUS'] = "CRASH_AFTER_LAUNCH"
                    if "order_ran" in self.get_communication_history():
                        with open("testresultsjson.txt", "a") as f:
                            f.write(",{\"order_ran\":\"0\", \"status\":\"Failed\", \"name\":\"GAME_LAUNCH_FAILURE\", \"class\":\"FATAL_ERROR\", \"test_categories\":\"LAUNCH_FAILURE\", \"result_details\":\"The game launched, and automation registered on the pubsub communication channel, but either the app crashed, or automation was blocked from beginning its test run.\", \"assertions\":[]},")
                    else:
                        with open("testresultsjson.txt", "w") as f:
                            f.write("[{\"order_ran\":\"0\", \"status\":\"Failed\", \"name\":\"GAME_LAUNCH_FAILURE\", \"class\":\"FATAL_ERROR\", \"test_categories\":\"LAUNCH_FAILURE\", \"result_details\":\"The game launched, and automation registered on the pubsub communication channel, but either the app crashed, or automation was blocked from beginning its test run.\", \"assertions\":[]},")

    def set_screenshot_dir(self, screenshot_dir):
        log("Saving screenshots at: " + screenshot_dir)
        self.screenshot_dir = screenshot_dir
        if not os.path.exists(screenshot_dir):
            os.mkdir(self.screenshot_dir)

    def take_screenshot(self, path):
        log("Attempting to save screenshot at path [" + self.screenshot_dir + path + "]")
        try:
            self.driver.save_screenshot(self.screenshot_dir + path)
        except Exception as e:
            log("Exception! " + str(e))

    def handle_device_alert(accept):
        if os.environ['DEVICE_PLATFORM'] == "android":
            # Try to dismiss any Android account alerts.
            try:
                acceptButton = self.driver.find_element_by_xpath("//*[@text='Allow']")
                action = TouchAction(self.driver)
                action.tap(acceptButton).perform()
                log("Chose 'Allow' for Google Play alert.")
            except Exception as e:
                log("Exception accepting Android alert! " + str(e))
            try:
                acceptButton = self.driver.find_element_by_xpath("//*[@text='OK']")
                action = TouchAction(self.driver)
                action.tap(acceptButton).perform()
                log("Chose 'OK' for Google Play alert.")
            except Exception as e:
                log("Exception accepting Android alert! " + str(e))
        else:
            log("Attempting to dismiss any iOS device-level alert.")
            try:
                if accept == True:
                    self.driver.switch_to.alert.accept()
                else:
                    self.driver.switch_to.alert.dismiss()
            except Exception as e:
                log("Internal Error Accepting iOS Alert (this is not likely a problem, due to interval dismissal logic): " + str(e))

    # Write name of self to parent level file that selected Buddy will check to verify both Buddy's have begun their test runs.
    def buddy_check_in(self):
        #directoryPieces = os.getcwd().split("/")
        #self.parentDirectory = ""
        #index = len(directoryPieces)
        #for piece in directoryPieces:
            #index -= 1
            #if index > 0:
                #self.parentDirectory += piece + "/"
        #with open(self.buddyCheckFileName, "a") as f:
            #f.write(self.gridIdentity)
        log("Writing Device Identity [" + self.gridIdentity + "] To File [" + self.buddyCheckFileName + "].")

    # See if Buddy has checked in as active and running. Will be used to skip Buddy tests if associated Buddy cannot perform its function.
    def buddy_check(self):
        return True
        #fileReadTest = ""
        #with open(self.buddyCheckFileName, "r") as f:
            #fileReadTest = f.read()
        #self.buddyCheckComplete = True
        log("Reading Buddy Check File. Expecting To See Buddy Name [" + self.buddyName + "] In File Contents [" + fileReadTest + "].")
        #if self.buddyName not in fileReadTest:
            #TODO: self.postMessage("{\"buddy_ignore_all\":0}")
            #return False
        #else:
            #return True

    # Break final XML generated by AutomationReport.cs out from total pubsub history and format it properly before placing it in final xml file.
    def get_xml_from_client_run(self):
        log("Command Recieved: [Get XML]")
        global test_run_id
        recent_posts = self.get_communication_history()
        # Toke "xml_complete" is required for this script to know that a client has reached completion of its test run.
        if ("xml_complete" not in recent_posts and "completed_automation" not in recent_posts) or self.parsing_xml == True:
            return False
        self.parsing_xml = True
        log("Xml Complete token detected. Begining parsing of test results xml.")
        time.sleep(5)
        
        # Split wall of pubsub text on start token and determine how many fragments of XML our test run intends to communicate.
        splitPieces = recent_posts.split("xml_start")
        if len(splitPieces) < 2:
            log("Failed to detect xml_start token in recent posts [" + recent_posts + "]")
            return False
        rawSplit = splitPieces[1]
        delimiter = "|"
        start = rawSplit.index(delimiter) + len(delimiter)
        end = rawSplit.index(delimiter, start)
        xmlPiecesCount = int(rawSplit[start:end])

        # XML is potentially fragmented when large test runs exceed a 4000 character pubsub message limit.
        log("XML Pieces Count [" + str(xmlPiecesCount) + "]")

        # PubNub does not guarantee sequential order of messages. We know how many xml fragments to expect, but not the order they will be recieved.
        xml_parsed = [None] * xmlPiecesCount
        list_history = recent_posts.split(test_run_id)

        # Split each fragment from history and place it into a dictionary that guarantees the proper order of reconstituted xml.
        for v in list_history:
            post = v
            if "xml_fragment_" in post:
                log("XML Fragment Detected. Parsing.")
                delimiter = "||"
                start = post.find(delimiter, 0) + 2
                end = post.find(delimiter, start + 2)
                index = int(post.split("xml_fragment_")[1][0])
                xml_parsed[index] = post[start:end]
        all_xml = ""
        for p in xml_parsed:
            if p != None:
                all_xml += p
        self.results = all_xml.replace('@APOS@', '"')
        if len(all_xml) == 0:
            log("XML empty after processing. Recent posts [" + recent_posts + "]")
        log("ALL_XML_FINAL " + all_xml)
        return True
            
    # Find, extract, format, and save all single-test JSON results for server HTML report
    def get_json_from_client_run(self, force):
        log("Command Recieved: [Get JSON]")
        recent_posts = self.get_communication_history()
        if "completed_automation" in recent_posts or force == True:
            log("Generating JSON.")
            initialDelimiter = "SINGLE_TEST_RESULTS_JSON|"
            delimiter = "|"
            rawAll = recent_posts.split(initialDelimiter)
            json = ""
            index = 0
            partialInitialDelimiter = "SINGLE_TEST_RESULTS_JSON_MULTI_PART|"
            for x in rawAll:
                if index > 0 and len(x) > 0:
                    # Handle test results reporting that was too large to send in a single message, requiring several parts of a single result report.
                    if partialInitialDelimiter in x:
                        rawPartials = x.split(partialInitialDelimiter) # All partial message pieces
                        indexPartial = 0
                        piecesFinal = ["" for x in range(len(rawPartials))]
                        for z in rawPartials:
                            if indexPartial == 0:
                                json += rawPartials[0].split(delimiter)[0] # First, record the test that preceded the partial test details report.
                            else:
                                piecesPartial = z.split(self.partialDataDelimiter)
                                piecesFinal[int(piecesPartial[0])] = piecesPartial[1].split(delimiter)[0] # The first piece after splicing is the index/order of this piece. Set that piece equal to the actual message data.
                            indexPartial += 1
                        for f in piecesFinal:
                            json += f # Should piece together valid json in correct order if previous for loop correctly handled ordering.
                    else:
                        json += x.split(delimiter)[0]
                index += 1
            
            # "@APOS@" token is a special encoding of double qoutes to prevent issues with PubNub message encoding and proper formatting of JSON
            json = json.replace("@APOS@", "\"").replace("}{", "},{")
            if not json.endswith("]"):
                if json.endswith(","):
                    json = json[:-1] + "]"
                else:
                    json += "]"
            fileContent = ""
            with open("testresultsjson.txt", "r") as f:
                fileContent = f.read()
            log("JSON FINAL LENGTH [" + str(len(json)) + "]")
            try:
                log("JSON FINAL ACTUAL [" + json + "]")
            except Exception as e:
                log("Failed to parse final json [" + str(e) + "]")
            if json not in fileContent:
                with open("testresultsjson.txt", "a") as f:
                    f.write(json)
            return True
        else:
            return False

    # This is used by the server to check for client "heartbeats", or to request them, to verify that client has not crashed or hanged in execution.
    def has_heartbeat(self):
        global heartbeats
        if self.last_heartbeat_detected == None:
            self.last_heartbeat_detected = datetime.now()

        if len(heartbeats) > 0:
            log("Registered heartbeat #" + str(self.heartbeat_index))
            self.heartbeat_index += 1
            self.last_heartbeat_detected = datetime.now()

        timeDifference = (datetime.now() - self.last_heartbeat_detected).total_seconds()
        if timeDifference > self.max_time_since_heartbeat:
            self.postMessage("{\"health_check\":0}")
            log("Any heartbeat ??" + heartbeats)
            time.sleep(15)
            if len(heartbeats) > 0:
                log("Registered heartbeat #" + str(self.heartbeat_index) + " after explicit request")
                self.heartbeat_index += 1
                self.last_heartbeat_detected = datetime.now()
                return True
            else:
                log("Heartbeat not detected in expected timeframe. Time since last heartbeat [" + str(timeDifference) + " seconds]")
                return False
        else:
            return True

    # Get pubsub history saved in text file with each recieved callback.
    def get_communication_history(self):
        results = ""
        try:
            with open("RelevantPubNubCommunications.txt", "r") as f:
                results = f.read()
        except Exception as e:
            log("Exception Reading History Text: " + str(e))
        return results

    # Get only the pubsub message history that contains a provided search term.
    def get_specific_json_from_history(self, jsonFlag):
        #Return only messages bound for this server-client relationship.
        historyText = self.get_communication_history()
        if len(historyText) == 0:
            return ""
        history = historyText.split("messageFull")
        global test_run_id
        resultsString = ""
        for x in history:
            rawMessage = urllib.unquote(str(x)).replace("\\", "").replace("\"", "'").replace("+", " ")
            splitMessage = rawMessage.split("test_run_id")
            for s in splitMessage:
                if test_run_id in s and (True if jsonFlag == None else (jsonFlag in s)):
                    resultsString += s
        return resultsString

    # See if client has requested the server take a screenshot.
    def check_for_client_requests(self, command):
        if command == "screenshot":
            fileName = ""
            with open("screenshot_requests.txt", "r") as f:
                fileName = f.read().strip()
            f = open("screenshot_requests.txt", "w")
            f.write("")
            f.close()
            if any(c.isalpha() for c in fileName):
                if "Interval" in fileName:
                    fileName = str(self.auto_screenshot_index) + "_" + "interval"
                    self.auto_screenshot_index += 1
                else:
                    fileName = "/" + fileName + ".png"
                    # If this file already exists, don't take it again.
                    if os.path.exists(self.screenshot_dir + fileName) == False:
                        try:
                            self.take_screenshot(fileName)
                            self.postMessage("{\"request_response\":\"screenshot\"}")
                            log("Screenshot successfully saved [" + fileName + "]")
                        except BaseException as e:
                            log("Exception Taking Screenshot! " + str(e))
        if command == "handle_client_commands":
            commandFull = ""
            with open("client_request_queue.txt", "r") as f:
                commandFull = f.read()
            if "|" in commandFull:
                # Handle command
                commandActual = commandFull.split("|")[0]
                commandValue = commandFull.split("|")[1]
                if commandActual == "HANDLE_DEVICE_ALERT":
                    self.handle_device_alert(False if commandValue == "0" else True)
                #Clear command queue
                f = open("client_request_queue.txt", "w")
                f.write("")
                f.close()
                self.postMessage("{\"server_broker_response\":\"" + commandActual + "\"}")
            else:
                try:
                    self.driver.switch_to.alert.accept()
                except BaseException as e:
                    log("")

    def find_json_for_performance_attribute(self, delimiter):
        recent_posts = self.get_communication_history()
        endDelimiter = "|"
        json = ""
        index = 0
        fullInitialDelimiter = delimiter + "_MULTI_PART|"
        rawAll = recent_posts.split(fullInitialDelimiter)
        piecesFinal = ["" for x in range(len(rawAll) - 1)]
        log("Finding " + delimiter)
        for x in rawAll:
            if index > 0 and len(x) > 0:
                # Handle test results reporting that was too large to send in a single message, requiring several parts of a single result report.
                rawPartials = x.split(fullInitialDelimiter) # All partial message pieces
                for z in rawPartials:
                    piecesPartial = z.split(self.partialDataDelimiter)
                    if index - 1 == int(piecesPartial[0]):
                        piecesFinal[int(piecesPartial[0])] = piecesPartial[1].split(endDelimiter)[0] # The first piece after splicing is the index/order of this piece. Set that piece equal to the actual message data.
                        break
            index += 1
        for f in piecesFinal:
            json += f # Should piece together valid json in correct order if previous for loop correctly handled ordering.

        # "@APOS@" token is a special encoding of double qoutes to prevent issues with PubNub message encoding and proper formatting of JSON
        json = json.replace("@APOS@", "\"").replace("}{", "},{")
        if not json.endswith("]"):
          json += "]"
        return json

    # Check if specific messages have been communicated over PubNub and extract relevant details.
    def check_for_client_responses(self, command, postAllParsed):
        historyString = ""
        if command == "heap_json":
            log("Collecting Heap Json")
            fileWrite = open("HeapJson.txt", "w")
            fileWrite.write(self.find_json_for_performance_attribute("HEAP_JSON"))
            fileWrite.close()
            return True
        if command == "garbage_collection_json":
            log("Collecting GC Json")
            fileWrite = open("GarbageCollectionJson.txt", "w")
            fileWrite.write(self.find_json_for_performance_attribute("GC_JSON"))
            fileWrite.close()
            return True
        if command == "fps_json":
            log("Collecting FPS Json")
            fileWrite = open("FpsJson.txt", "w")
            fileWrite.write(self.find_json_for_performance_attribute("FPS_JSON"))
            fileWrite.close()
            return True
        if command == "exceptions_data":
            log("Collecting Exceptions Values")
            fileWrite = open("ExceptionsJson.txt", "w")
            fileWrite.write(self.find_json_for_performance_attribute("EXCEPTION_DATA"))
            fileWrite.close()
            return True
        if command == "garbage_collection":
            historyString = self.get_specific_json_from_history("GARBAGE_COLLECTION")
            if len(historyString) > 0:
                log("Collecting Garbage Collection Values")
                initialDelimiter = "GARBAGE_COLLECTION|"
                finalDelimiter = "|"
                raw = historyString.split(initialDelimiter)[1]
                data = raw.split(finalDelimiter)[0]
                fileWrite = open("GarbageCollection.txt", "w")
                fileWrite.write(data)
                fileWrite.close()
                return True
        if command == "heap_size":
            historyString = self.get_specific_json_from_history("HEAP_SIZE")
            if len(historyString) > 0:
                log("Collecting Heap Size Values")
                initialDelimiter = "HEAP_SIZE|"
                finalDelimiter = "|"
                raw = historyString.split(initialDelimiter)[1]
                data = raw.split(finalDelimiter)[0]
                fileWrite = open("HeapSize.txt", "w")
                fileWrite.write(data)
                fileWrite.close()
                return True
        if command == "fps":
            historyString = self.get_specific_json_from_history("FPS_VALUES")
            if len(historyString) > 0:
                log("Collecting FPS Values")
                initialDelimiter = "FPS_VALUES|"
                finalDelimiter = "|"
                raw = historyString.split(initialDelimiter)[1]
                data = raw.split(finalDelimiter)[0]
                fileWrite = open("Fps.txt", "w")
                fileWrite.write(data)
                fileWrite.close()
                return True
        if command == "game_launch_seconds":
            historyString = self.get_specific_json_from_history("GAME_LAUNCH_SECONDS")
            if len(historyString) > 0:
                log("Collecting Game Initialization Time")
                initialDelimiter = "GAME_LAUNCH_SECONDS|"
                finalDelimiter = "|"
                raw = historyString.split(initialDelimiter)[1]
                data = raw.split(finalDelimiter)[0]
                fileWrite = open("GameInitializationTime.txt", "w")
                fileWrite.write(data)
                fileWrite.close()
                return True
        if command == "device_details_html":
            historyString = self.get_specific_json_from_history("DEVICE_DETAILS_HTML")
            if len(historyString) > 0:
                log("Collecting Device Details HTML")
                initialDelimiter = "DEVICE_DETAILS_HTML|"
                finalDelimiter = "|"
                raw = historyString.split(initialDelimiter)[1]
                html = raw.split(finalDelimiter)[0].replace("@APOS@", "\"").replace("@QUOT@", "'")
                fileWrite = open("TestRunHeaderHtml.txt", "w")
                fileWrite.write(html)
                fileWrite.close()
                return True

        recent_posts = self.get_communication_history()
        if command == "ready" and ("checking_in" in recent_posts or "DBID||" in recent_posts):
             time.sleep(5)
             if "DBID||" in recent_posts:
                 dbidPiece = recent_posts.split("DBID||")[1]
                 self.DBID = dbidPiece.split("||")[0]
             return True
        if command == "started" and ("starting_automation" in recent_posts or "Starting Automation" in recent_posts or "SINGLE_TEST_RESULTS_JSON" in recent_posts):
            return True
        if command == "complete" and "completed_automation" in recent_posts:
            return True
        if command == "fatal_error_check" and "Fatal Error. Shutting down automation" in recent_posts:
            if self.fatalErrorDetected == False:
                self.fatalErrorDetected = True
                self.fatalErrorMessage = "Fatal Error popup occurred. Game Unavailable!"
                self.take_screenshot("/fatal_error.png")
            return True
        return False
Beispiel #36
0
def error(message):
    print("ERROR : " + str(message))


def connect(message):
    print("CONNECTED")
    print(
        pubnub.publish(channel=channel,
                       message='Hello from the PubNub Python SDK'))


def reconnect(message):
    print("RECONNECTED")


def disconnect(message):
    print("DISCONNECTED")


# Read every N seconds and publish to Pubnub
while (True):
    temperature = {}
    temp_value = sensor.get_temperature()
    temp_date_pubnub = time.strftime("%Y-%m-%d %H:%M:%S")
    temp_date_lcd = time.strftime("%Y-%m-%d %H:%M")
    temperature["value"] = temp_value
    temperature["date"] = temp_date_pubnub
    pubnub.publish(channel, temperature, error=error)
    lcd.write_string("Temp: " + str(temp_value) + "\r\n" + temp_date_lcd)
    time.sleep(sleep_interval)
Beispiel #37
0
class MessageChannel:
    command_key = "command"
    successfully_processed_command_key = "successfully_processed_command"

    def __init__(self, channel, temperature_servo, oled):
        self.temperature_servo = temperature_servo
        self.oled = oled
        self.channel = channel
        # Do not forget to replace the string with your publish key
        publish_key = "pub-c-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
        # Subscribe key is the one that usually starts with the "sub-c" prefix
        # Do not forget to replace the string with your subscribe key
        subscribe_key = "sub-c-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
        self.pubnub = Pubnub(publish_key=publish_key, subscribe_key=subscribe_key)
        self.pubnub.subscribe(channels=self.channel,
                              callback=self.callback,
                              error=self.callback,
                              connect=self.connect,
                              reconnect=self.reconnect,
                              disconnect=self.disconnect)

    def callback_response_message(self, message):
        print("I've received the following response from PubNub cloud: {0}".format(message))

    def error_response_message(self, message):
        print("There was an error when working with the PubNub cloud: {0}".format(message))

    def publish_response_message(self, message):
        response_message = {
            self.__class__.successfully_processed_command_key:
                message[self.__class__.command_key]}
        self.pubnub.publish(
            channel=self.channel,
            message=response_message,
            callback=self.callback_response_message,
            error=self.error_response_message)

    def callback(self, message, channel):
        if channel == self.channel:
            print("I've received the following message: {0}".format(message))
            if self.__class__.command_key in message:
                if message[self.__class__.command_key] == "print_temperature_fahrenheit":
                    self.temperature_servo.print_temperature(message["temperature_fahrenheit"])
                    self.publish_response_message(message)
                elif message[self.__class__.command_key] == "print_information_message":
                    self.oled.print_line(11, message["text"])
                    self.publish_response_message(message)

    def error(self, message):
        print("Error: " + str(message))

    def connect(self, message):
        print("Connected to the {0} channel".
              format(self.channel))
        print(self.pubnub.publish(
            channel=self.channel,
            message="Listening to messages in the Intel Galileo Gen 2 board"))

    def reconnect(self, message):
        print("Reconnected to the {0} channel".
              format(self.channel))

    def disconnect(self, message):
        print("Disconnected from the {0} channel".
              format(self.channel))
Beispiel #38
0
#!/usr/bin/python
from pubnub import Pubnub

pubnub = Pubnub(publish_key="pub-c-5b4ed4d3-8921-45cb-8151-d48aaebb2467",
                subscribe_key="sub-c-f7b16a98-a291-11e6-a1b1-0619f8945a4f")

channel = "onboard"
message = "done"
pubnub.publish(channel=channel, message="done")
    reading = 0
    GPIO.setup(RCpin, GPIO.OUT)
    GPIO.output(RCpin, GPIO.LOW)
    time.sleep(0.1)

    GPIO.setup(RCpin, GPIO.IN)
    while (GPIO.input(RCpin) == GPIO.LOW):
        reading += 1
    return reading

while True:
    lightVal = 0
    
    for i in range (0 , 60):
        lightVal += RCtime(18)
        
    lightVal = 100/(lightVal/60)
    #humidity, temperature = read(DHT11, 17)
    
    print('Sending light value of ' + str(lightVal) + ' onto weather channel')
    #print('Temperature should be ' + str(temperature))
    #print('Humidity should be ' + str(humidity))

    data = {
        'light': lightVal
        }
    
    
    pubnub.publish(channel = channelW,
                   message = data)
import os
import time
import sys
from pubnub import Pubnub
import Adafruit_DHT as dht

pubnub = Pubnub(publish_key='demo', subscribe_key='demo')
channel = 'tempeon'

def callback(message):
    print(message)

#published in this fashion to comply with Eon
while True:
    h,t = dht.read_retry(dht.DHT22, 4)
    print 'Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(t, h)
    pubnub.publish('tempeon', {
        'columns': [
            ['x', time.time()],
            ['temperature_celcius', t]
            ]

        })
    pubnub.publish('humeon', {
        'columns': [
            ['humidity', h]
            ]

        })
Beispiel #41
0
from pubnub import Pubnub

pubnub = Pubnub(publish_key="your pub key", subscribe_key="your sub key")

print(pubnub.publish(channel='your channel name', message='your msg'))
          
        def connect(message):
            print("CONNECTED")
            print pubnub.publish(channel='my_channel', message='Hello from the PubNub Python SDK')
          
          
          
        def reconnect(message):
            print("RECONNECTED")
          
          
        def disconnect(message):
            print("DISCONNECTED")
      
      
        pubnub.subscribe(channels='my_channel', callback=callback, error=callback,
                         connect=connect, reconnect=reconnect, disconnect=disconnect)

        pubnub.publish('my_channel', {
                    'columns': [
                        ['x', time.time()],
                        ['temperature_celcius', temperature]
                        ]

                    });           
          
    except Exception as e:
        print 'error',str(e)
   

Beispiel #43
0
import sys
from pubnub import Pubnub

pubnub = Pubnub(publish_key='pub-c-df137065-b5ca-4b1d-841a-3f547ec9b6f0',
                subscribe_key='sub-c-875a6a50-d26d-11e5-b684-02ee2ddab7fe')

channel = 'hello'

data = {'username': '******', 'message': 'Hello World from Pi!'}


def callback(m):
    print(m)


pubnub.publish(channel, data, callback=callback, error=callback)
Beispiel #44
0
def pn_publish(message):
    if not message:
        return

    pn = Pubnub(publish_key=cfg.PUBKEY, subscribe_key=cfg.SUBKEY)
    pn.publish(channel=cfg.OGCHAN, message=message)
Beispiel #45
0
from pubnub import Pubnub

pubnub = Pubnub(publish_key="pub-c-b0397ad5-c7e4-4b7e-b5a3-e7b41637b984",
                subscribe_key="sub-c-b487e99c-3c9e-11e8-8bb7-3ab51ec5ed79")
channel = "my_channel"
message = "A message"

pubnub.publish(channel=channel, message="A message")
Beispiel #46
0
import sys
from pubnub import Pubnub

pubnub = Pubnub(publish_key='pub-c-dc523a3b-b81c-430d-9eb6-37ffa0c9053c', subscribe_key='sub-c-2e3bb45c-1f8e-11e5-9dff-0619f8945a4f')

channel = 'iot_garage_sensor'
data = { 'username': '******',
         'message': 'Hello world from Pi!'}

def callback(m):
   print(m)

pubnub.publish(channel, data, callback=callback, error=callback)
Beispiel #47
0
	if result.is_valid():
		return result.temperature , result.humidity
	
	return -1,-1
def callback(message):
	print(message)


while True:
    t , h = getTempHumidity()

    if ( t != -1 ):
    	print ( " temperature = %d \n " % t )
    	print ( " humidity = %d \n " % h )
	print 'Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(t, h)
    	pubnub.publish('tempeon', {
        	'columns': [
            	'x': time.time(),
            	'temperature_celcius': t
            	]

        	})
    	pubnub.publish('humeon', {
        	'columns': [
            	['humidity', h]
            	]

        	})

    time.sleep(1)
    ##Use the distance measurement as a proximity alarm.
    ##Set 'distance' in if-loop to desired alarm distance.
    ##When the alarm is tripped, the distance and a note are sent as a dictionary in a PubNub message, and the sensor stops searching.

    if distance <= 10:
        print("Distance:", distance, "cm")
        print("Proximity Detected")

        for i in range(6):
            GPIO.output(LIGHT, True)
            time.sleep(0.03)
            GPIO.output(LIGHT, False)
            time.sleep(0.03)
        message = {'distance': distance, 'Proximity': "True"}
        print pubnub.publish(channel, message)
        time.sleep(.3)

##If nothing is detected, the sensor continuously sends and listens for a signal, and publishes the distance to your PubNub channel.
    else:
        print("Time", pulse_duration)
        print("Distance", distance, "cm")
        print("Too Far")

        message = {'distance': distance, 'Proximity': 'False'}
        print pubnub.publish(channel, message)

    time.sleep(.3)

#Clean up GPIO pins + reset
GPIO.cleanup()
Beispiel #49
0
def publish_rate():
    pubnub = Pubnub(publish_key='demo', subscribe_key='demo', ssl_on=False)
    info = pubnub.publish(channel=CHANNEL, message=get_rate())
Beispiel #50
0
# -*- coding: utf-8 -*-
import os
import time
import sys
from pubnub import Pubnub
import Adafruit_DHT as dht

pubnub = Pubnub(publish_key='demo', subscribe_key='demo')
channel = 'pi-house'

def callback(message):
    print(message)

#published in this fashion to comply with Eon
while True:
    h,t = dht.read_retry(dht.DHT22, 4)
    temp={0:0.1f}.format(t)
    hum={1:0.1f}.format(h)
    message = {'temperature': temp, 'humidity': hum}
    print 'Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(t, h)
    pubnub.publish(channel=channel, message=message, callback=callback, error=callback)


Beispiel #51
0
import sys
from pubnub import Pubnub

## -----------------------------------------------------------------------
## Initiate Pubnub State
## -----------------------------------------------------------------------
pubnub = Pubnub(
    publish_key='pub-c-c9bc3d23-4bc7-44a7-a1dc-c2d1f9445a25',
    subscribe_key='sub-c-22a3eac0-0971-11e5-bf9c-0619f8945a4f',
    secret_key='sec-c-NGQ0MzU5NTUtMWYxZi00YTBiLWIzNGEtZDBhNmFlY2JkZTFi',
    cipher_key=cipher_key,
    ssl_on=ssl_on,
    pooling=False)
channel = 'test'
message = 'file name'

# Synchronous usage
print pubnub.publish(channel, message)


# Asynchronous usage
def callback(message):
    print(message)


pubnub.publish(channel, message, callback=callback, error=callback)
    
##Use the distance measurement as a proximity alarm.
##Set 'distance' in if-loop to desired alarm distance.
##When the alarm is tripped, the distance and a note are sent as a dictionary in a PubNub message, and the sensor stops searching.

    if distance <= 10:
        print("Distance:",distance,"cm")
        print("Proximity Detected")

        for i in range(6):
            GPIO.output(LIGHT,True)
            time.sleep(0.03)
            GPIO.output(LIGHT,False)
            time.sleep(0.03)
        message = {'distance': distance, 'Proximity': "True"}
        print pubnub.publish(channel, message)
        time.sleep(.3)
       

##If nothing is detected, the sensor continuously sends and listens for a signal, and publishes the distance to your PubNub channel.    
    else:
        print("Time", pulse_duration)
        print("Distance", distance, "cm")
        print("Too Far")

        message = {'distance': distance, 'Proximity' : 'False'}
        print pubnub.publish(channel, message)
        
    time.sleep(.3)

Beispiel #53
0
import os
import time
import sys
from pubnub import Pubnub
import Adafruit_DHT as dht

pubnub = Pubnub(publish_key='#####',
                subscribe_key='sub-c-02190da8-ebc6-11e9-bdee-36080f78eb20')

#published in this fashion to comply with Eon
while True:

    h, c = dht.read_retry(dht.DHT11, 4)
    h = float(h)
    c = float(c)
    f = (c * 1.8) + 32

    pubnub.publish('thompson-hydroponics-temp',
                   {'eon': {
                       'celcius': c,
                       'farenheight': f,
                       'humidity': h
                   }})

    time.sleep(900)  # 15 minutes
Beispiel #54
0
from pubnub import Pubnub

pubnub = Pubnub(publish_key="publish_key", subscribe_key="subscribe_key")

print(pubnub.publish(channel='my_channel', message="on"))
Beispiel #55
0
#main
print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)

if len(sys.argv) < 2:
    print "Number of args is wrong. Going to exit"
    exit(-1)

global stopScript
stopScript = False
signal.signal(signal.SIGINT, signal_handler)

pubnub = Pubnub(publish_key="pub-c-55470b0a-fe27-4763-b774-3aa63111fee0",
                subscribe_key="sub-c-783f7138-b7bd-11e6-91e2-02ee2ddab7fe")
channelName = sys.argv[1]

time.sleep(10)

while True:
    humdity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.AM2302, 4)
    humdity -= 7
    now = time.strftime("%d/%m/%Y-%H:%M:%S")
    room = Room('bedroom', round(temperature, 2), round(humdity, 2), now)
    pubnub.publish(channel=channelName, message=room.__dict__)
    print("Send message to pubnub")
    print(room.__dict__)
    time.sleep(300)
    if stopScript:
        break
Beispiel #56
0
class SmartGarden:
    def update(self, sessionToken, username):
        self.username = username
        self.sessionToken = sessionToken
        self.temperature = 0
        self.humidity = 0
        self.moisture = 0
        self.light = 0
        self.waterNow = False
        grovepi.pinMode(constants.LIGHT_PIN,"INPUT")
        grovepi.pinMode(constants.MOISTURE_PIN,"INPUT")
        grovepi.pinMode(constants.TEMP_HUMIDITY_PIN,"INPUT")
        grovepi.pinMode(constants.PUMP_RELAY_PIN,"OUTPUT")
        self.pubnub = Pubnub(publish_key=constants.PUBNUB_PUBLISH_KEY, subscribe_key=constants.PUBNUB_SUBSCRIBE_KEY, ssl_on = True)
        self.sendSensors = False
        while True: #keep trying until you have internet
            try:
                req = urllib2.Request(constants.ROOT_URL + 'active-plant')
                req.add_header('x-access-token', sessionToken)
                result = json.loads(urllib2.urlopen(req).read())

                self.waterAmount = result["waterAmount"]
                self.harvest = len(result["harvests"])
                self.moistureLimit = result["moistureLimit"]                
                break
            except Exception as e:
                s = str(e)
                
    def __init__(self, sessionToken, username):
        self.update(sessionToken, username)

    def ioLoop(self):
        while True:            
            time.sleep(.2)
            if self.sendSensors:
                while self.waterNow:
                    time.sleep(.1)                    
                self.readSensors()                
                data = {
                    "humidity":self.humidity,
                    "light":self.light,
                    "moisture":self.moisture,
                    "temperature":self.temperature                                    
                }
                self.pubnub.publish(self.username + constants.WEBSITE_CHANNEL, data)

    def sendDataDb(self, water = False):
        if self.sendSensors:
            time.sleep(.3)  #wait long enough for it to read, it should have already read a bunch but this is just to make sure
        else:
            self.readSensors()
        data = {
            "humidity":self.humidity,
            "light":self.light,
            "moisture":self.moisture,
            "temperature":self.temperature,
            "harvest":self.harvest,
            "water": self.waterAmount if water else 0,
        }
        while True:
            try:
                req = urllib2.Request(constants.ROOT_URL + 'sensor-data')
                req.add_header('Content-Type', 'application/json')
                req.add_header('x-access-token', self.sessionToken)
                response = urllib2.urlopen(req, json.dumps(data)).read()
                break
            except Exception as e:
                s = str(e)                

    def sendDataDbAndCheckWater(self):
        while True:
            time.sleep(900) #every 15 minutes
            if self.sendSensors:
                time.sleep(.3)  #wait long enough for it to read
            else:
                self.readSensors()
            if self.moisture < self.moistureLimit:
                self.waterPlants()
            else:
                self.sendDataDb()

    def waterPlants(self):        
        self.waterNow = True
        grovepi.digitalWrite(constants.PUMP_RELAY_PIN,1)
        time.sleep(self.waterAmount / constants.FLOW_RATE)
        grovepi.digitalWrite(constants.PUMP_RELAY_PIN,0)
        grovepi.digitalWrite(constants.PUMP_RELAY_PIN,0)
        grovepi.digitalWrite(constants.PUMP_RELAY_PIN,0)
        self.waterNow = False
        self.sendDataDb(True)        

    def readSensors(self):
        try:
            while True:
                [ temperature, humidity ] = dht(constants.TEMP_HUMIDITY_PIN,0)
                moisture = grovepi.analogRead(constants.MOISTURE_PIN)
                light = grovepi.analogRead(constants.LIGHT_PIN)
                if temperature < 200 and temperature >= 0 and humidity >=0 and humidity <= 100 and moisture >= 0 and moisture <= 700 and light >= 0 and light <= 700:
                    self.temperature = temperature
                    self.humidity = humidity
                    self.moisture = moisture
                    self.light = light
                    break
        except Exception as e:
            self.readSensors() #keep trying until it works
Beispiel #57
0
from pubnub import Pubnub
pubnub = Pubnub(publish_key='pub-c-0bb87cba-798a-4074-a4c4-ef877921331e',
                subscribe_key='sub-c-7a3fc736-ed8c-11e5-8f88-0619f8945a4f')


def callback(message):
    print message


def _callback(message, channel):
    print "S :", message


def _error(message):
    print(message)


pubnub.subscribe(channels="monument_channel", callback=_callback, error=_error)

import serial
ser = serial.Serial('/dev/cu.SLAB_USBtoUART')
# ser.timeout = 1
while True:
    rfid = ser.read(12)
    print rfid
    pubnub.publish(
        'monument_channel',
        "[{latlng: [28.617748,77.195100],marker: me},{latlng: [28.6177,77.2011],marker: them},{latlng: [28.6172,77.1910],marker: them},{latlng: [28.617748,77.195100],marker: them},{latlng: [28.6174,77.19544],marker: them},{latlng: [28.617467,77.2022],marker: them}];",
        callback=callback,
        error=callback)
Beispiel #58
0

import sys
from pubnub import Pubnub

publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo'
subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo'
secret_key = len(sys.argv) > 3 and sys.argv[3] or 'demo'
cipher_key = len(sys.argv) > 4 and sys.argv[4] or ''
ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False

# -----------------------------------------------------------------------
# Initiate Pubnub State
# -----------------------------------------------------------------------
pubnub = Pubnub(publish_key=publish_key, subscribe_key=subscribe_key,
                secret_key=secret_key, cipher_key=cipher_key, ssl_on=ssl_on, pooling=False)
channel = 'hello_world'
message = 'Hello World !!!'


# Synchronous usage
print(pubnub.publish(channel, message))

# Asynchronous usage


def callback(message):
    print(message)

pubnub.publish(channel, message, callback=callback, error=callback)
    return -1


while True:
    try:
        # Read distance value from Ultrasonic
        uSDist = ultrasonicRead(ultrasonic_ranger)
        #       print uSDist
        if (uSDist > 0):
            stream.add_value(int(uSDist))

        #read the button
        buttonValue = grovepi.digitalRead(button)
        #       print buttonValue
        if buttonValue > 0:
            pubnub.publish(channel, message="reset")
#       if uSDist < 10:
#               pubnub.publish(channel,
#                       message = "on")
#               stream.add_value(int(uSDist))
#               print "less 10: %d" % (uSDist)
#       else:
#                pubnub.publish(channel,
#                        message = "off")
#               stream.add_value(int(uSDist))
#               print "not less 10: %d" % (uSDist)

        time.sleep(.5)
    except TypeError:
        print "Error"
    except IOError: