def setup_subscription(self):
        dprint("get:", SessionManager.instance().get_session())

        if self.use_other_session == False:
            self.m_client.subscribe(
                'commandResponse', [SessionManager.instance().get_session()],
                callback=self.subscription_response_callback)

        self.m_client.subscribe('imageviewerdb',
                                [SessionManager.instance().get_session()],
                                callback=self.subscription_image_callback)
 def getSession_callback(self, error, result):
     if error:
         dprint("getSession_callback error")
         dprint(error)
         return
     print("in getSession_callback, sessionID:", result)
     if self.use_other_session == False:
         SessionManager.instance().set_session(result)
     # subscribe response
     # subscribe imageController
     # observe response, imageController
     self.setup_subscription()
Exemple #3
0
    def send_command(self,
                     cmd,
                     parameter,
                     built_callback=None,
                     user_callback=""):
        # 有built_callback就先處理它. 然後有user_callback就async,  沒有就直接return result
        # 沒有built_callback就建一個dummmy, 然後裡面再callback user_callback
        # 沒有user_callback就要把self.sync_resp_queue.put
        # 也有可能都沒有
        print("send command".format("cmd"))
        identifier = cmd + parameter
        #const id = cmd + parameter;

        # cmd_dict = {'if_async': if_async, 'callback': callback}
        cmd_dict = {
            'id': identifier,
            'built_callback': built_callback,
            'user_callback': user_callback
        }

        self.mutex.acquire()
        self.callbacks.append(cmd_dict)
        self.mutex.release()
        self.client.call(
            sendCmd, [cmd, parameter,
                      SessionManager.instance().get_session()],
            self.send_command_callback)
        if user_callback == None:
            data = self.block_for_user_callback()
            return data
        else:
            print("async send command !!!!!")
 def saveDataToCollection(self, collection, newDocObject, actionType):
     sessionID = SessionManager.instance().get_session()
     docs = self.m_client.find(collection,
                               selector={'sessionID': sessionID})
     total = len(docs)
     if total > 0:
         dprint("try to replace first image in mongo, total images:", total)
         doc = docs[0]
         docID = doc["_id"]
         newDocObject["sessionID"] = sessionID
         # update, not test yet
         self.m_client.update(collection, {'_id': docID},
                              newDocObject,
                              callback=self.update_callback)
     else:
         # insert
         dprint("try to to insert images")
         newDocObject["sessionID"] = sessionID
         self.m_client.insert(collection,
                              newDocObject,
                              callback=self.insert_callback)
         dprint("end to insert")
    def handleAddedOrChanged(self, collection, id, fields):
        for key, value in fields.items():
            dprint('  - FIELD {}'.format(key))
            # dprint('  - FIELD {} {}'.format(key, value))

        if collection == "users":
            dprint("grimmer users added/changed ")
        elif collection == "responses":
            dprint("grimmer responses added/changed, self_sessionID:",
                   fields["sessionID"])

            if "pushedImage" in fields:
                # if "buffer" in fields:
                imgString = fields["buffer"]
                imageLeng = len(imgString)
                print("get image, data size in (cmd) response:", imageLeng)

                #TODO the dummy empty images should be solved in the future, but now we use it to judge connect ok
                if imageLeng > 10012:
                    # url = "data:image/jpeg;base64,"+imgString
                    # save to mongo for share screen
                    #TODO python: forget to setup controllerID. js: forget to add size
                    self.saveDataToCollection('imageviewerdb', {
                        "imageURL": imgString,
                        "size": len(imgString)
                    }, GET_IMAGE)
                    #save file for testing
                    # dprint("try to save image")
                    # self.render_received_image(imgString)

                    # imgdata = base64.b64decode(imgString)
                    # filename = currentTime +".jpg"  # I assume you have a way of picking unique filenames
                    # with open(filename, 'wb') as f:
                    #     f.write(imgdata)
                    #
                    #     if run_from_interactive():
                    #         # img = mpimg.imread('1.jpg'), from file
                    #         i = io.BytesIO(imgdata)
                    #         i = mpimg.imread(i, format='JPG') # from memory, binary
                    #
                    #         # plt.imshow(i, interpolation='nearest')
                    #         #TODO let mainthread to redraw
                    #         imgplot = plt.imshow(i)# may be no difference
                    #         plt.pause(0.01)
                    #     else:
                    #         dprint("not ipython, so do no show image after saving")

                # global numberOfImages
                # self.numberOfImages += 1
                # if self.numberOfImages == 2:
                #     print("get dummy 2 images")
                #     self.sync_connected_queue.put(connect_response)
            elif "cmd" in fields:
                self.receive_response(fields)
            #2.  remove it, may not be necessary for Browser, just aligh with React JS Browser client
            self.m_client.remove('responses', {'_id': id},
                                 callback=self.remove_callback)

        elif collection == 'imageviewerdb':
            sessionID = SessionManager.instance().get_session()
            docs = self.m_client.find(collection,
                                      selector={'sessionID': sessionID})
            total = len(docs)
            print("imagecontroller added/changed event happens, total docs:",
                  total)
            if total > 0:
                # firstDoc = docs[0]
                for doc in docs:
                    docID = doc["_id"]
                    dprint("loop image collection, id is", docID)
                    #NOTE since meteor-python does not have Optimistic update so that we need to remove old images after getting added/changed callback
                    if docID != id:
                        print("remove one image document")
                        self.m_client.remove(
                            'imageviewerdb', {'_id': docID},
                            callback=self.remove_image_callback)
                        # global testimage
                        # testimage +=1
                        # if testimage ==1:
                        #     dprint("try 2nd image file")
                        #     ImageController.selectFileToOpen2(client)
                        #
                        # doc["comments"] = "apple"
                        # for testing client.update('imageviewerdb', {'_id': docID}, {"name": "ggg"}, callback=update_callback)
                        # for testing
                        # client.update('imageviewerdb', {'_id': docID}, doc, callback=update_callback)
                    else:
                        dprint("not remove it")
                        print("image size in collection:",
                              len(doc["imageURL"]))
                        self.render_received_image(doc["imageURL"])
 def watch_other_session(self, session):
     SessionManager.instance().use_other_session(session)
     self.use_other_session = True