def testCode8Case2(self):  
        """resettoken when have microgear.cache while microgear is offline"""
        self.assertTrue(os.path.isfile(os.path.join(os.getcwd()+"/microgear.cache")))

        self.assertIsNone(microgear.gearkey)
        self.assertIsNone(microgear.gearsecret)    
        self.assertIsNone(microgear.appid)
        
        client.create(self.gearkey, self.gearsecret, self.appid)
       
        client.on_connect = MagicMock()

        client.resettoken()
        self.assertFalse(os.path.isfile(os.path.join(os.getcwd()+"/microgear.cache")))
        client.connect()
        time.sleep(connect_timeout)
        self.assertTrue(client.on_connect.called)
        self.assertEqual(client.on_connect.call_count, 1)
        self.assertTrue(os.path.isfile(os.path.join(os.getcwd()+"/microgear.cache")))

    

# def main():
    # pass
#     #suite = unittest.TestSuite()
#     #suite.addTest(TestChat("testCode4Case2"))
#     #runner = unittest.TextTestRunner()
#     #runner.run(suite)
#     print(os.path.join(os.getcwd(),"microgear.cache"))    
#     unittest.main()

# if __name__ == '__main__':
#     main()    
Esempio n. 2
0
    def testCode6Case1(self):  
        """unsubscribe the subscribed topic"""
        print('Code6Case1')
        try: 
            print("run helper...")
            code = str(51)
            args = ['python', 'helper.py', code]
            p = subprocess.Popen(args, cwd=(helper_dir))
            time.sleep(connect_worst_timeout)

            client.create(self.gearkey, self.gearsecret, self.appid)
           
            client.on_connect = MagicMock()
            client.on_message = MagicMock()
          
            client.connect()
            time.sleep(connect_timeout)
            self.assertTrue(client.on_connect.called)
            self.connected = True
            self.assertEqual(client.on_connect.call_count, 1) 

            client.subscribe(self.topic)
            time.sleep(message_timeout)
            self.assertTrue(client.on_message.called)
            client.unsubscribe(self.topic)
            client.on_message.reset_mock()
            self.assertFalse(client.on_message.called)
            time.sleep(message_timeout)
            self.assertFalse(client.on_message.called)
            p.kill()

        #if fails due to assertion error
        except Exception as e:
            p.kill()
            raise Exception(e.args) 
Esempio n. 3
0
    def testCode6Case2(self):  
        """unsubscribe the topic before subscribe""" 
        print('Code6Case2')

        print(microgear.gearkey)
 
        try:
            print("run helper...")
            code = str(51)
            args = ['python', 'helper.py', code]
            p = subprocess.Popen(args, cwd=(helper_dir))
            time.sleep(connect_worst_timeout)
            print(microgear.gearkey)
            client.create(self.gearkey, self.gearsecret, self.appid)

            client.on_connect = MagicMock()
            client.on_message = MagicMock()
          
            client.connect()
            time.sleep(connect_timeout)
            self.assertTrue(client.on_connect.called)
            self.connected = True
            self.assertEqual(client.on_connect.call_count, 1) 
            self.assertFalse(client.on_message.called)
            client.unsubscribe(self.topic)
            self.assertFalse(client.on_message.called)
            client.subscribe(self.topic)
            time.sleep(message_timeout)
            self.assertTrue(client.on_message.called)
            client.on_message.assert_called_with(self.expectedTopic, self.expectedMessage)
            p.kill()

        except Exception as e:
            p.kill()
            raise Exception(e.args) 
Esempio n. 4
0
def testCreateNetPieLabel():
    gearkey, gearsecret, appid = testCreateNetPie1();
    client.create(gearkey, gearsecret, appid, {'label' : "Microgear Python"})
    client.setname('logg')
    client.connect()
    print("Sleep for 90 seconds")
    time.sleep(90)
Esempio n. 5
0
    def testCode4Case2(self):
        """chat with other microgear in same appid"""
        try:
            print('Code4Case2')  
            print("run helper...")
            code = str(31)
            args = ['python', 'helper.py', code]
            p = subprocess.Popen(args, cwd=(helper_dir))
            time.sleep(connect_worst_timeout)

            print("run main...")
            client.create(self.gearkey, self.gearsecret, self.appid)
            client.setalias(self.gearname)

            client.on_connect = MagicMock()
            
            client.connect()
            time.sleep(connect_timeout)

            self.assertTrue(client.on_connect.called)
            self.connected = True
            client.chat(self.helperGearname, self.message)
            time.sleep(message_timeout)
            r_file = open(receiver_file, "r")
            received_message = r_file.read()
            r_file.close()        
            if(received_message == self.message):
                self.received = True
            self.assertTrue(self.received)
            p.kill()
        #if fails due to assertion error
        except Exception as e:
            print("fail")
            raise Exception(e.args)
Esempio n. 6
0
    def testCode7Case5(self):
        """publish invalid topic - no slash"""
        try:
            print("run helper...")
            code = str(61)
            args = ['python', 'helper.py', code]
            p = subprocess.Popen(args, cwd=(helper_dir))
            time.sleep(connect_worst_timeout)

            self.invalidTopic = "firstTopic"
            
            client.create(self.gearkey, self.gearsecret, self.appid)
           
            client.on_connect = MagicMock()
          
            client.connect()
            time.sleep(connect_timeout)
            self.assertTrue(client.on_connect.called)
            self.connected = True
            self.assertEqual(client.on_connect.call_count, 1)

            client.publish(self.invalidTopic, self.message)
            time.sleep(message_timeout)

            receiver_file = open(os.path.join(os.getcwd(),"receiver.txt"), "r")
            received_message = receiver_file.read()
            receiver_file.close()
            if(received_message == self.message):
                self.received = True
            self.assertFalse(self.received)
            self.assertTrue(client.on_connect.call_count > 1)
            p.kill()
        except Exception as e:
            p.kill()
            raise Exception(e.args) 
Esempio n. 7
0
def connectTo():
    gearkey = "qnlgzsPUUxYeyQP"
    gearsecret = "1euJPvxybllEPQZzq2u9wpRJXDbjM7"
    appid = "testNo3"    
    client.create(gearkey, gearsecret, appid, {'debugmode': "True"})
    
    def on_connected():
        print("connect")
    def on_closed():
        print("close")  
    def on_rejected():
        print("reject")     
    def on_error():
        print("error")  
    def on_message():
        print("message")  
    def on_present():
        print("present")
    def on_absent():
        print("absent") 
    client.on_connect = on_connected
    client.on_error = on_error
    client.on_present = on_present
    client.on_absent = on_absent
    client.on_rejected = on_rejected
    client.on_closed = on_closed
    client.on_message = on_message
    logs = LogCapture()
    client.connect()
    print(logs)
    logs.check(('root', 'DEBUG', 'Check stored token.'))
Esempio n. 8
0
    def testCode5Case6x2(self):
        """subscribe invalid topic - no slash"""
        try:
            print('Code5Case6x2')   
            print("run helper...")
            code = str(53)
            args = ['python', 'helper.py', code]
            p = subprocess.Popen(args, cwd=(helper_dir))
            time.sleep(connect_worst_timeout)

            self.topic = "firstTopic"

            client.create(self.gearkey, self.gearsecret, self.appid)
            client.subscribe(self.topic)
       
            client.on_connect = MagicMock()
            client.on_message = MagicMock()
           
            client.connect()
            time.sleep(connect_timeout)
            self.assertTrue(client.on_connect.called)
            self.connected = True
            self.assertEqual(client.on_connect.call_count, 1)
            time.sleep(message_timeout)
            self.assertFalse(client.on_message.called)  
            p.kill()

                                    #if fails due to assertion error
        except Exception as e:
            p.kill()
            raise Exception(e.args)
Esempio n. 9
0
def test():
    gearkey = "qnlgzsPUUxYeyQP"
    gearsecret = "1euJPvxybllEPQZzq2u9wpRJXDbjM7"
    appid = "testNo3"    
    if(os.path.isfile("microgear.cache")):
        f = open((os.getcwd() + "/microgear.cache"), 'r')
        print(f.readlines())
        f.close()  
    
    else:
        print("yes1")       
    client.create(gearkey, gearsecret, appid, {'debugmode': "True", 'scope': "chat:receiver"})
    client.setname("sender")
    if(os.path.isfile("microgear.cache")):
        f = open((os.getcwd() + "/microgear.cache"), 'r')
        print(f.readlines())
        f.close() 
    else:
        print("yes2")    
    client.connect()
    f = open((os.getcwd() + "/microgear.cache"), 'r')
    print(f.readlines())
    f.close()
    client.resettoken()
    if(os.path.isfile("microgear.cache")):
        f = open((os.getcwd() + "/microgear.cache"), 'r')
        print(f.readlines())
        f.close()
    else:
        print("yes3")
Esempio n. 10
0
def testCreateNetPieScopeName():
    gearkey, gearsecret, appid = testCreateNetPie1();
    client.create(gearkey, gearsecret, appid, {'debugmode' : True, 'scope' : "name:logger"})
    client.setname('logg')
    client.connect()
    print("Sleep for 90 seconds")
    time.sleep(90)
Esempio n. 11
0
    def testCode5Case2(self):   
        """subscribe same topic twice"""
        try:
            print('Code5Case2')
            print("run helper...")
            code = str(51)
            args = ['python', 'helper.py', code]
            p = subprocess.Popen(args, cwd=(helper_dir))
            time.sleep(connect_worst_timeout)

            client.create(self.gearkey, self.gearsecret, self.appid)
            client.subscribe(self.topic)
            client.subscribe(self.topic)
            client.on_connect = MagicMock()
            client.on_message = MagicMock()
           
            client.connect()
            time.sleep(connect_timeout)
            self.assertTrue(client.on_connect.called)
            self.connected = True
            self.assertEqual(client.on_connect.call_count, 1)   

            time.sleep(message_timeout)
            self.assertTrue(client.on_message.called)
            client.on_message.assert_called_with(self.expectedTopic, self.expectedMessage)
            p.kill()
                            #if fails due to assertion error
        except Exception as e:
            p.kill()
            raise Exception(e.args)
Esempio n. 12
0
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)
        self.peano_flag =None
        self.sensor = Sensor()
        self.setupUi(self)
        self.config = None
        self.capture = Capture(self)
        self.fileDiag = QFileDialog()
        self.img_path = None
        self.live_flag = None
        # self.thread_2 = self.v2_sl.value()
        # self.thread_1 = self.v1_sl.value()
        # self.tableWidget.setColumnCount(3)
        # self.tableWidget.resizeColumnsToContents()
        # self.tableWidget.resizeRowsToContents()

        self.start_cam_btn.clicked.connect(self.capture.startCapture)
        self.stop_cam_btn.clicked.connect(self.capture.endCapture)
        self.snap_btn.clicked.connect(self.snap_handler)
        self.exit_btn.clicked.connect(exit_handler)
        self.pick_btn.clicked.connect(self.get_file)
        self.detect_btn.clicked.connect(self.detect_api)
        self.detect_btn.setDisabled(True)
        # self.v1_sl.valueChanged.connect(self.v1_changed)
        # self.v2_sl.valueChanged.connect(self.v2_changed)

        # self.measure_btn.clicked.connect(self.measure)
        # self.count_btn.clicked.connect(self.count)

        self.circle_radio.toggled.connect(lambda: self.btnstate(self.circle_radio))
        self.unknow_radio.toggled.connect(lambda: self.btnstate(self.unknow_radio))
        self.livepreview.toggled.connect(lambda: self.btnstate(self.livepreview))
        self.peano_chk.toggled.connect(lambda: self.btnstate(self.peano_chk))


        self.object_type = None

        self.label.setAutoFillBackground(True)
        self.label.setText("Wait for Connection ..")
        self.label.setStyleSheet('color: blue')

        self.Timer = QTimer()
        self.Timer.timeout.connect(self.check_status)
        self.Timer.start(15000)

        self.gearkey = 'liLGrIH0WZdAKT0'  # key
        self.gearsecret = 'OfFLXs2NlqL3ecjkaClXhEUli'  # secret
        self.appid = 'ImageRaspi'
        try: # TODO : comment if don't need netpie.
            client.create(self.gearkey, self.gearsecret, self.appid, {'debugmode': True})
            client.on_connect = self.callback_connect
            client.setalias("doraemon")
            client.on_message = self.callback_message
            client.on_error = self.callback_error
            client.subscribe("/mails")
            client.connect()
        except Exception as e:
            pass
Esempio n. 13
0
def testAlias():
    gearkey = "qnlgzsPUUxYeyQP"
    gearsecret = "1euJPvxybllEPQZzq2u9wpRJXDbjM7"
    appid = "testNo3"    

    client.create(gearkey, gearsecret, appid, {'debugmode': "True", 'alias': "Python"})
    client.connect()
    while True:
        pass
Esempio n. 14
0
 def testConnectWillBlockFalse(self):
     self.connected = False
     def on_connected():
         self.connected = True
     client.on_connect = on_connected
     client.create(self.gearkey, self.gearsecret, self.appid, {'debugmode': "True"})   
     client.connect(False)
     timeout = time.time() + 30.0
     if(time.time() > timeout or self.connected):
         self.assertTrue(self.connected)
Esempio n. 15
0
def testCreateNetPieConnection():
    gearkey, gearsecret, appid = testCreateNetPie1();
    client.create(gearkey, gearsecret, appid, {'debugmode' : False})
    
    def on_connection():
        print "I am connected"
    client.on_connect = on_connection
    print(client.on_connect == 0)
    client.connect()
    print("Sleep for 100 seconds")
    time.sleep(100)
Esempio n. 16
0
def testCreateNetPieScopeChat():
    gearkey, gearsecret, appid = testCreateNetPie1();
    client.create(gearkey, gearsecret, appid, {'debugmode' : True, 'scope' : "chat:java ja"})
    client.setname('Python ja')
    client.connect()
    
    def receive_message(topic, message):
        print topic + " " + message
    
    while(True):
        client.chat('Html ka', "Hello html")
        time.sleep(3)
        client.on_message = receive_message
def testChat():
    gearkey = "ExhoyeQoTyJS5Ac"
    gearsecret = "gzDawaaHRe1KvQhepAw3WYuuGHjBsh"
    appid = "p107microgear"

    origin = "oriA"
    destination = "destX"
    
    client.create(gearkey , gearsecret, appid, {'debugmode': True})
    bf = open(os.path.join(os.getcwd(),"microgear.cache"), "rb")
    print(bf)
    client.resettoken()
    af = open(os.path.join(os.getcwd(),"microgear.cache"), "rb")
    print(af)
Esempio n. 18
0
def testScopeChat():
    gearkey = "qnlgzsPUUxYeyQP"
    gearsecret = "1euJPvxybllEPQZzq2u9wpRJXDbjM7"
    appid = "testNo3"    

    client.create(gearkey, gearsecret, appid, {'debugmode': "True", 'scope': "chat:receiver"})
    client.setname("sender")
    client.connect()
    
    def receive_message(topic, message):
        print topic + " " + message
    
    while True:
        client.chat("not receiver","How are you?")
        time.sleep(3) 
Esempio n. 19
0
 def testCode4Case1(self):
     """chat with itself"""   
     print('Code4Case1')
    
     client.create(self.gearkey, self.gearsecret, self.appid)
     client.setalias(self.gearname)
     client.on_message = MagicMock()
     client.on_connect = MagicMock()
     client.connect()
     time.sleep(connect_timeout)
     self.assertTrue(client.on_connect.called)
     self.connected = True
     client.chat(self.gearname, self.message)
     time.sleep(message_timeout)
     self.assertTrue(client.on_message.called)
     client.on_message.assert_called_once_with(self.expectedMsgTopic, self.expectedMessage)
Esempio n. 20
0
def testCreateNetPieScopeW():
    gearkey = "ExhoyeQoTyJS5Ac"
    gearsecret = "gzDawaaHRe1KvQhepAw3WYuuGHjBsh"
    appid = "p107microgear"
    client.create(gearkey , gearsecret, appid, {'debugmode': True,'scope': "r:/LetsShare" })
    client.create(gearkey , gearsecret, appid, {'debugmode': True,'scope': "w:/LetsShare" })
    client.setname("Python ja")
    client.connect()
    
    def receive_message(topic, message):
        print topic + " " + message
    
    while True:
        client.publish("/StopsShare","Happy New Year!")
        time.sleep(3)
        client.on_message = receive_message
    def testCode8Case1(self):  
        """resettoken when no microgear.cache
            pre-requisite: no microgear.cache file""" 
        if(os.path.isfile(microgear_cache)):
            os.remove(microgear_cache)

        self.assertIsNone(microgear.gearkey)
        self.assertIsNone(microgear.gearsecret)    
        self.assertIsNone(microgear.appid)
        
        client.create(self.gearkey, self.gearsecret, self.appid)
       
        client.on_connect = MagicMock()

        client.resettoken()
        self.assertFalse(os.path.isfile(microgear_cache))
Esempio n. 22
0
def testChat():
    gearkey = "ExhoyeQoTyJS5Ac"
    gearsecret = "gzDawaaHRe1KvQhepAw3WYuuGHjBsh"
    appid = "p107microgear"

    origin = "oriA"
    destination = "destX"
    client.create(gearkey , gearsecret, appid, {'debugmode': True})
    client.setname(origin)
    client.connect()

    def receive_message(topic, message):
        print topic + " " + message

    while True:
        client.chat(destination,"Hello world.")
        time.sleep(3)
def testChat():
    gearkey = "ExhoyeQoTyJS5Ac"
    gearsecret = "gzDawaaHRe1KvQhepAw3WYuuGHjBsh"
    appid = "p107microgear"

    gear_name = "not receiver"

    client.create(gearkey , gearsecret, appid, {'debugmode': True})
    client.setname(gear_name)
    client.connect()

    def receive_message(topic, message):
        print topic + " " + message

    while True:
        client.chat("not receiver", "hello")
        time.sleep(3)
        client.on_message = receive_message
def testResetToken():
    gearkey = "ExhoyeQoTyJS5Ac"
    gearsecret = "gzDawaaHRe1KvQhepAw3WYuuGHjBsh"
    appid = "p107microgear"
 
    client.create(gearkey , gearsecret, appid, {'debugmode': True})
    client.setname("Python ja")
    client.setname("Not Python ja")

    client.connect()
    
    def receive_message(topic, message):
        print topic + " " + message
    
    while True:     
        time.sleep(3)
        print("hello")
        client.on_message = receive_message
    def testCode8Case2(self):  
        """resettoken when have microgear.cache while microgear is offline"""
        #pre-requisite: ensure there is microgear.cache
  

        self.assertIsNone(microgear.gearkey)
        self.assertIsNone(microgear.gearsecret)    
        self.assertIsNone(microgear.appid)
        client.create(self.gearkey, self.gearsecret, self.appid, {'debugmode': True})
        client.connect(False)
        self.assertTrue(os.path.isfile(microgear_cache))
        #resettoken when have microgear.cache
        
        client.resettoken()

        time.sleep(4)
        #should delete microgear.cache
        self.assertFalse(os.path.isfile(microgear_cache))
Esempio n. 26
0
    def testCode5Case4(self):   
        """subscribe the topic that it publishes"""
        print('Code5Case4')
        client.create(self.gearkey, self.gearsecret, self.appid)
        client.subscribe(self.topic)
   
        client.on_connect = MagicMock()
        client.on_message = MagicMock()
       
        client.connect()
        time.sleep(connect_timeout)
        self.assertTrue(client.on_connect.called)
        self.connected = True
        self.assertEqual(client.on_connect.call_count, 1)

        client.publish(self.topic, self.message)
        time.sleep(message_timeout)
        self.assertTrue(client.on_message.called)
        client.on_message.assert_called_with(self.expectedTopic, self.expectedMessage)
Esempio n. 27
0
    def testCode4Case6(self):
        """chat with other microgear which shares the same gearname in different appid"""
        try:
            print('Code4Case6')
            print("run helper...")
            code = str(12)
            args = ['python', 'helper.py', code]
            p = subprocess.Popen(args, cwd=(helper_dir))
            time.sleep(connect_worst_timeout)   

            print("run main...")
            self.helperGearname = self.gearname

            client.create(self.gearkey, self.gearsecret, self.appid)
            client.setalias(self.gearname)

            client.on_connect = MagicMock()
            client.on_message = MagicMock()
            
            client.connect()
            time.sleep(connect_timeout)
            self.assertTrue(client.on_connect.called)
            self.connected = True
            client.chat(self.helperGearname, self.message)
            time.sleep(message_timeout)

            self.assertTrue(client.on_message.called)
            client.on_message.assert_called_once_with(self.expectedMsgTopic, self.expectedMessage)
            
            receiver_file = open(os.path.join(os.getcwd(),"receiver.txt"), "r")
            received_message = receiver_file.read()
            receiver_file.close()
            if(received_message == self.message):
                self.received = True
                
            self.assertFalse(self.received)
            p.kill()
                    #if fails due to assertion error
        except Exception as e:
            p.kill()
            raise Exception(e.args)
Esempio n. 28
0
    def testCode6Case5x1(self):  
        """unsubscribe the invalid topic - no slash"""
        try:
            print("run helper...")
            code = str(51)
            args = ['python', 'helper.py', code]
            p = subprocess.Popen(args, cwd=(helper_dir))
            time.sleep(connect_worst_timeout)

            self.invalidStr = "firstTopic"
     
            client.create(self.gearkey, self.gearsecret, self.appid)
           
            client.on_connect = MagicMock()
            client.on_message = MagicMock()
          
            client.connect()
            time.sleep(connect_timeout)
            self.assertTrue(client.on_connect.called)
            self.connected = True
            self.assertEqual(client.on_connect.call_count, 1)
            self.assertFalse(client.on_message.called)
            client.subscribe(self.topic)
            time.sleep(message_timeout)
            self.assertTrue(client.on_message.called)
            client.on_message.assert_called_with(self.expectedTopic, self.expectedMessage)

            client.on_message.reset_mock()
            self.assertFalse(client.on_message.called)

            client.unsubscribe(self.invalidStr)
            time.sleep(connect_timeout)
            self.assertTrue(client.on_message.called)
            client.on_message.assert_called_with(self.expectedTopic, self.expectedMessage)
            p.kill()
        except Exception as e:
            p.kill()
            raise Exception(e.args) 
    def testCode8Case3(self):  
        """resettoken twice"""

        self.assertIsNone(microgear.gearkey)
        self.assertIsNone(microgear.gearsecret)    
        self.assertIsNone(microgear.appid)

        client.create(self.gearkey, self.gearsecret, self.appid, {'debugmode': True})
        client.connect(False)
        self.assertTrue(os.path.isfile(microgear_cache))

        client.resettoken()
        self.assertFalse(os.path.isfile(microgear_cache))
        client.resettoken()
        self.assertFalse(os.path.isfile(microgear_cache))

        client.on_connect = MagicMock()
        #should not affect connect
        client.connect()
        time.sleep(connect_timeout)
        self.assertTrue(client.on_connect.called)
        self.assertEqual(client.on_connect.call_count, 1)
        self.assertTrue(os.path.isfile(microgear_cache))
Esempio n. 30
0
    def testCode4Case10(self):
        """chat to topic which has subscriber"""
        try:   
            print('Code4Case10')
            print("run helper...")
            code = str(61)
            args = ['python', 'helper.py', code]
            p = subprocess.Popen(args, cwd=(helper_dir))
            time.sleep(connect_worst_timeout)

            print("run main...")
            self.gearname = '/firstTopic'


            client.create(self.gearkey, self.gearsecret, self.appid)
            client.setalias(self.gearname)

            client.on_connect = MagicMock()
            client.connect()
            time.sleep(connect_timeout)
            self.assertTrue(client.on_connect.called)
            self.connected = True

            client.chat(self.helperGearname, self.message)
            time.sleep(message_timeout)

            receiver_file = open(os.path.join(os.getcwd(),"receiver.txt"), "r")
            received_message = receiver_file.read()
            receiver_file.close()
            if(received_message == self.message):
                self.received = True
            self.assertFalse(self.received)
            p.kill()
                            #if fails due to assertion error
        except Exception as e:
            p.kill()
            raise Exception(e.args)
Esempio n. 31
0
import json
import microgear.client as client
import time

gearkey = "Djmh3H2yte6CIrW"
gearsecret = "43J9u4sJmMe34omGvLdu51JF74prLT"
appid = "NSC2016SEAH"

client.create(gearkey, gearsecret, appid)


def connection():
    print "Now I am connected with netpie"


def subscription(topic, message):
    print topic + " " + message
    with open('data.json', 'w') as outfile:
        data = '{\"value1\":" + float(message) +",\"value2\":300}'
        json.dump(data, outfile)


client.setalias("server")
client.on_connect = connection
client.on_message = subscription
client.subscribe("/Value")

client.connect(True)
import microgear.client as microgear
import cv2
import numpy as np
import imutils
from imutils.video import VideoStream
import time
import argparse

key = 'your key'
secret = 'your secret key'
app = 'your app id'
microgear.create(key,secret,app,{'debugmode': True})
connected = False

def connection():
    global connected
    connected = True
    print("Connected")
    
def callback_error(msg) :
    print(msg)

def callback_reject(msg) :
    print (msg)
    print ("Script exited")
    exit(0)
def subscription(topic,msg):
    if msg == "b'?'":
        microgear.publish("/countPeople",countPeople)

def CheckLineCrossing(centerMove, CoorExitLine1, CoorExitLine2):
Esempio n. 33
0
GPIO.setup(40,GPIO.OUT)
GPIO.output(40, GPIO.HIGH)
sleep(3)
GPIO.output(40, GPIO.LOW)
"""
appid = "EkkawinV"
gearkey = "UX0O5uKTBZuOjEw"
gearsecret = "xN2sMvgEp9Z3y1RB75J76LpSN"

ALIAS = "RaspberryPi"
thing = "FreeBoardTESR"

FEEDID = "EkkawinFeedTraining"
APIKEY = "0C8mmFd3USPXz3UPS287xgDaAcVk5YQJ"

microgear.create(gearkey, gearsecret, appid)


def connection():
    print("Now I am connected with netpie")


def subscription(topic, message):
    print(topic + " " + message)
    if "ON" in message:
        microgear.chat(thing, "ON," + ("%.1f" % netpie))
        GPIO.output(LED, GPIO.HIGH)
    elif "OFF" in message:
        microgear.chat(thing, "OFF," + ("%.1f" % netpie))
        GPIO.output(LED, GPIO.LOW)
Esempio n. 34
0
#    global message
#    pub = rospy.Publisher('command', String, queue_size=10)
#    rospy.init_node('talkerApp', anonymous=True)
#    pub.publish(message)
#    rate = rospy.Rate(10) # 10hz
#    while not rospy.is_shutdown():
#        hello_str = "hello world %s" % rospy.get_time()
#        rospy.loginfo(hello_str)
#        pub.publish(hello_str)
#        rate.sleep()

#//////////////////////Netpie///////////////////////////////////
appid = "HappyIoT Naja"
gearkey = "HappyIoT Naja"
gearsecret =  "HappyIoT Naja"
client.create(gearkey,gearsecret,appid,{'debugmode': True})

def connection():
	print "Now I am connected with netpie"

def subscription(topic,message):
    pub.publish(message)
    print topic+" "+message

client.setname("doraemon")
client.on_connect = connection
client.on_message = subscription
client.subscribe("/mails")

client.connect(True)
#//////////////////////////////////////////////////////////////
Esempio n. 35
0
import microgear.client as client
import logging
import time

appid = "ekaratnida"
gearkey = 'jtD9ag08syPtqiK'  # key
gearsecret = 'vDEEIuw9Ssj4OvbrBHmM4hZfa'  # secret

client.create(gearkey, gearsecret, appid,
              {'debugmode': True})  # สร้างข้อมูลสำหรับใช้เชื่อมต่อ

client.setalias("ekarat")  # ตั้งชื่้อ


def callback_connect():
    print("Now I am connected with netpie")


def callback_message(topic, message):
    print(topic, ": ", message)


def callback_error(msg):
    print("error", msg)


client.on_connect = callback_connect  # แสดงข้อความเมื่อเชื่อมต่อกับ netpie สำเร็จ
client.on_message = callback_message  # ให้ทำการแสดงข้อความที่ส่งมาให้
client.on_error = callback_error  # หากมีข้อผิดพลาดให้แสดง
client.subscribe(
    "/test"
Esempio n. 36
0
import microgear.client as microgear
import logging
from time import sleep
import spidev
import RPi.GPIO as IO
from mocoptor import *
from coptrix import *
from coplenoid import *

### MICROGEAR ###
APPID = "bellybluegw"
GEARKEY = "cGK3ij44dENtsPV"
GEARSECRET = "BwLvRGd4Gro4S3cMZiIMbfh9H"

microgear.create(GEARKEY, GEARSECRET, APPID, {'debugmode': True})
 
def connection():
    logging.info("Now I am connected with netpie")
    
def subscription(topic, message):
    logging.info(topic + " " + message)

def disconnect():
    logging.info("disconnected")
    
microgear.setalias("bot")
microgear.on_connect = connection
microgear.on_message = subscription
microgear.on_disconnect = disconnect
microgear.subscribe("/botcmd")
microgear.connect()
Esempio n. 37
0
import microgear.client as microgear
import time
import logging

appid = <Unbalance>
gearkey = <hGCHSVuHP92G1Xk>
gearsecret =  <IdLciZCa6M4SHjmc7Edt2NE64>

microgear.create(gearkey,gearsecret,appid,{'debugmode': True})

def connection():
    logging.info("Now I am connected with netpie")

def subscription(topic,message):
    logging.info(topic+" "+message)

def disconnect():
    logging.debug("disconnect is work")

microgear.setalias("doraemon")
microgear.on_connect = connection
microgear.on_message = subscription
microgear.on_disconnect = disconnect
microgear.subscribe("/mails")
microgear.connect(False)

while True:
	if(microgear.connected):
		microgear.chat("doraemon","Hello world."+str(int(time.time())))
	time.sleep(3)
Esempio n. 38
0
import preference.SharedPreferences as sp
import Database as db
import Time as t
import Controls as ctrl
import Clock as alarmClock

minuteStamp =  60 # 1 mintue in time stamp
hourStamp = 3600 # 1 hour in time stamp
con = False

appId = "<App Id>"
appKey = "<Gear Key>"
appSecret =  "<Gear Secret>"
hasReload = False

microgear.create(appKey,appSecret,appId,{'debugmode': True})
sp.getSharedPreferences()

def isHasReload():
    global hasReload
    if(hasReload):
        hasReload = False
        return True
    
def isConnect():
    global con
    return con

def publis(topic,payload):
    if(isConnect()):
        print("Microgear, publish topic: "+str(topic)+" to netpie")
Esempio n. 39
0
import microgear.client as microgear
import time
import logging

appid = <appid>
gearkey = <gearkey>
gearsecret =  <gearsecret>

microgear.create(gearkey,gearsecret,appid,{'debugmode': True})

def connection():
    logging.info("Now I am connected with netpie")

def subscription(topic,message):
    logging.info(topic+" "+message)

def disconnect():
    logging.debug("disconnect is work")

microgear.setalias("doraemon")
microgear.on_connect = connection
microgear.on_message = subscription
microgear.on_disconnect = disconnect
microgear.subscribe("/mails")
microgear.connect(False)

while True:
	if(microgear.connected):
		microgear.chat("doraemon","Hello world."+str(int(time.time())))
	time.sleep(3)
Esempio n. 40
0
import microgear.client as netpie
import time
import base64
from picamera import PiCamera
from io import BytesIO
import zlib

key = '<your key>'
secret = '<your secret key>'
app = '<application name>'

netpie.create(key,secret,app,{'debugmode': True})
connected = False

def connection():
 global connected
 connected = True
 print("Connected")
 
def subscription(topic,msg):
 global this_role,ready_to_send
 if this_role == 'reciever' :
  decode_base64(msg,None) # don't need to save on disk
  running=False
 else :
  if not ready_to_send :
   if msg =='iamok':
    ready_to_send = True
    print "Reciever is ready"
  
   
Esempio n. 41
0
import microgear.client as microgear
import time
import requests
import socket

appid = "EGATWeatherStation"
gearkey = "kXYcGquYNJf26je"
gearsecret = "PVREFWnv8fWEE497iBcCMpsLj"

microgear.create(gearkey, gearsecret, appid, {'debugmode': True})

t = 0
h = 0
c = 0


def connection():
    print("Now I am connected with netpie")


def subscription(topic, message):
    global t, h, c
    print(topic + " " + message)

    if topic == "/EGATWeatherStation/station1/temperature1":
        t = message
#	print(t)
    if topic == "/EGATWeatherStation/station1/humid":
        h = message
#	print(h)
    if topic == "/EGATWeatherStation/station1/temperature2":
Esempio n. 42
0
class StartWindows(QMainWindow):
    def __init__(self, camera=None, parent=None):
        super(StartWindows, self).__init__(parent=parent)
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.detections = None
        self.frame = None
        self.files = []
        self.tmp = []
        self.start = 0

        self.update_timer = QTimer()
        self.update_timer.timeout.connect(self.update)

        #User
        self.Qr_User = ""
        self.Point = 0

        #button
        self.ui.pushButton_2.clicked.connect(self.yolo_tiny)
        self.ui.pushButton.clicked.connect(self.stop)
        #camera
        self.camera = cv2.VideoCapture(0)
        self.update_timer.start(30)
        #qr
        self.qr = cv2.QRCodeDetector()
        '''
    def update2(self):
        self.update_timer2.start(30)
        ret,self.frame =self.camera.read()
        self.frame=cv2.flip(self.frame,1)
        cv2.imshow("img", img)  
        '''

    def connection():
        print("Now I am connected with netpie")

    def subscription(topic, message):
        logging.info(topic + " " + message)

    def disconnect():
        logging.debug("disconnect is work")

    appid = "ProjectOs"
    gearkey = "B0r3CNqaRtDjDf0"
    gearsecret = "qRjL4WFFGCZqXY6hkpHFKkLIx"
    client.create(gearkey, gearsecret, appid, {'debugmode': True})
    client.setname("doraemon")
    client.on_connect = connection
    client.on_message = subscription
    client.subscribe("/mails")

    client.connect()

    def yolo_tiny(self):

        self.start = 1

        self.execution_path = os.getcwd()
        self.detector = ObjectDetection()
        self.detector.setModelTypeAsTinyYOLOv3()
        self.detector.setModelPath(
            os.path.join(self.execution_path, "yolo-tiny.h5"))
        self.detector.loadModel(detection_speed="flash")
        print("###you are use yolo_tiny model###")

    def update(self):

        if (self.start == 0):
            print("QR")

            ret, self.frame = self.camera.read()

            decodedObjects = pyzbar.decode(self.frame)

            for obj in decodedObjects:
                if obj.data:

                    self.Qr_User = str(obj.data)
                    self.Qr_User = self.Qr_User[2:len(self.Qr_User) - 1]

            print(self.Qr_User)
            self.frame = cv2.flip(self.frame, 1)
            self.frame = cv2.resize(self.frame, (891, 501))
            height, width, channel = self.frame.shape
            bytesPerLine = 3 * width

            qImg = QImage(self.frame.data, width, height, bytesPerLine,
                          QImage.Format_RGB888).rgbSwapped()
            pixmap01 = QPixmap.fromImage(qImg)
            pixmap_image = QPixmap(pixmap01)
            self.ui.label.setPixmap(pixmap_image)
            self.ui.user_id.setText(self.Qr_User)

            self.ui.label.show()

        if (self.start == 1):
            ret, self.frame = self.camera.read()
            self.frame = cv2.flip(self.frame, 1)
            #detected
            custom_objects = self.detector.CustomObjects(bottle=True)
            detected_image_array, self.detections = self.detector.detectCustomObjectsFromImage(
                custom_objects=custom_objects,
                input_type="array",
                input_image=self.frame,
                output_type="array")
            for eachObject in self.detections:

                print(eachObject["name"], " : ",
                      (eachObject["percentage_probability"]), " : ",
                      eachObject["box_points"])

                if int(eachObject["percentage_probability"]) >= 50:
                    self.Point += 1
                    time.sleep(0.5)

                    print(self.Point)

            #resize

            detected_image_array = cv2.resize(detected_image_array, (891, 501))
            height, width, channel = detected_image_array.shape
            bytesPerLine = 3 * width

            qImg = QImage(detected_image_array.data, width, height,
                          bytesPerLine, QImage.Format_RGB888).rgbSwapped()
            pixmap01 = QPixmap.fromImage(qImg)
            pixmap_image = QPixmap(pixmap01)
            self.ui.label.setPixmap(pixmap_image)
            self.ui.user_id.setText(self.Qr_User)
            self.ui.user_point.setText(str(self.Point))

            self.ui.label.show()

    ''' 
    def score():
        d=self.detections
        for eachObject in d:
          
            if int(eachObject["percentage_probability"]) >=50 :
                self.Point+=1
                print(self.Point)
           '''

    def stop(self):
        #ส่งข้อมูลช่วงนี้ก่อนแล้วเคลียค่า
        print(self.Qr_User)
        print(self.Point)
        client.publish("/Point2", str(self.Point))
        client.publish("/Name", str(self.Qr_User))
        client.publish("/Mix", (str(self.Qr_User) + "," + str(self.Point)))

        self.start = 0
        self.Qr_User = ""
        self.Point = 0
        self.ui.user_point.setText(str(self.Point))
        print(self.Qr_User)
        print(self.Point)

    def start(self):
        self.update_timer.start(30)