Exemplo n.º 1
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)
Exemplo n.º 2
0
def LED_State(message):
    print(message)
    if message == "b'ON'":
        GPIO.output(Red_LED, 1)
        GPIO.output(Green_LED, 1)
        GPIO.output(Blue_LED, 1)
        LED_State = 1
        microgear.chat("LED-Status", LED_State)
    elif message == "b'OFF'":
        GPIO.output(Red_LED, 0)
        GPIO.output(Green_LED, 0)
        GPIO.output(Blue_LED, 0)
        LED_State = 0
        microgear.chat("LED-Status", LED_State)
    elif message == "b'RED'":
        GPIO.output(Red_LED, 1)
        GPIO.output(Green_LED, 0)
        GPIO.output(Blue_LED, 0)
    elif message == "b'GREEN'":
        GPIO.output(Red_LED, 0)
        GPIO.output(Green_LED, 1)
        GPIO.output(Blue_LED, 0)
    elif message == "b'BLUE'":
        GPIO.output(Red_LED, 0)
        GPIO.output(Green_LED, 0)
        GPIO.output(Blue_LED, 1)
Exemplo n.º 3
0
def controlTag(number,Order_bool):
    send = ""
    if Order_bool is True:
        send = str(number) + "," + "ON"
        microgear.chat("client_Tag_control",send)
    elif Order_bool is False:
        send = str(number) + "," + "OFF"
        microgear.chat("client_Tag_control",send)
Exemplo n.º 4
0
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)
Exemplo n.º 5
0
def subscription(topic,message):
    logging.info(topic+" "+message)
    print message
    if message == "ON":
        GPIO.output(11,GPIO.HIGH)
        microgear.chat("HTML_web", "ON")
    else:
        GPIO.output(11,GPIO.LOW)
        microgear.chat("HTML_web", "OFF")
Exemplo n.º 6
0
def read_temp():
    lines = read_temp_raw()
    while lines[0].strip()[-3:] != 'YES':
        time.sleep(0.2)
        lines = read_temp_raw()
    equals_pos = lines[1].find('t=')
    if equals_pos != -1:
        temp_string = lines[1][equals_pos + 2:]
        temp_c = float(temp_string) / 1000.0
        temp_f = temp_c * 9.0 / 5.0 + 32.0
        print "Temp:", temp_c
        microgear.chat("TEMPWATER", temp_c)
Exemplo n.º 7
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
Exemplo n.º 8
0
def subscription(topic, msg):
    global this_role, ready_to_receive
    if this_role == 'receiver':
        if not ready_to_receive:
            if msg == 'ruok':
                netpie.chat(those_name, 'iamok')
                ready_to_receive = True

        else:
            print "recieving image data."
            decode_base64(msg, None)  # don't need to save on disk
            print "process is done"
    else:
        print(topic + ":" + msg)
Exemplo n.º 9
0
def subscription(topic,msg):
 global this_role,ready_to_receive 
 if this_role == 'receiver' :
  if not ready_to_receive :
   if msg=='ruok' :
    netpie.chat(those_name,'iamok')
    ready_to_receive = True
    
  else : 
   print "recieving image data."
   decode_base64(msg,None) # don't need to save on disk
   print "process is done"
 else :
  print(topic+":"+msg)
Exemplo n.º 10
0
def reaction(data):
    if data is not '':
        microgear.publish('/speech',"You : " + data)
        if "how are you" in data or data in ("how are you","how do you feel") :
            speak("I am fine")
    
        if "what time" in data:
            speak(ctime())

        if "turn on light" in data:
            speak("Ok turn on the light")
            microgear.chat("lightEdge",'1')

        if "turn off light" in data:
            speak("Ok turn off the light")
            microgear.chat("lightEdge",'0')

        if "turn off air" in data:
            speak("Ok turn off Air condition")
            microgear.chat("AIRCONSWITCH",'10')

        if "turn on air" in data:
            speak("Ok turn on Air condition")
            microgear.chat("AIRCONSWITCH",'11')

        if "where is" in data:
            data = data.split(" ")
            location = data[2]
            speak("Hold on, I will show you where " + location + " is.")
            os.system("chromium-browser https://www.google.nl/maps/place/" + location + "/&")
Exemplo n.º 11
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) 
Exemplo n.º 12
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)
Exemplo n.º 13
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)
Exemplo n.º 14
0
def subscription(topic,msg):
 global this_role,ready_to_receive,running
 if this_role == 'receiver' :
  if not ready_to_receive :
   if msg=='ruok' :
    netpie.chat(those_name,'iamok')
    ready_to_receive = True   
        
  else : 
   #print ("recieving image data.")
   decode_base64(msg,None) # don't need to save on disk
   #print ("process is done")
   #print ("----- "+ str(count) + " ------")
   running = False
      
   
 else :
Exemplo n.º 15
0
def initial_Val(message):
    global set_initial
    a = message.split(",")
    # print a
    # print a[0] ,"a0"
    # print a[1] ,"a1"
    if str(a[1]) == "startinitValue":
        # print "Do"
        microgear.chat("WebServer", "init,-53")
        # microgear.chat("WebServer","-53")
        # microgear.chat("WebServer","ready")
        set_initial = True
        # print "start",a[0] , a[1]
        # rule.returnChat("-53")
    elif str(a[1]) == "stopinitValue":
        # microgear.chat("WebServer","ok done")
        set_initial = False
Exemplo n.º 16
0
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
Exemplo n.º 17
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)
Exemplo n.º 18
0
def searchALL(dic, number):
    global before, count_reset, set_before, set_ESP
    # print dic
    number = number - 1
    for i, j in dic.items():
        for a in range(0, len(tagRoom)):
            if i == tagRoom[a][0]:
                intitial_ewma(j, a, number)
                if int(
                        ewma_backward(before[number][a], j) -
                        ewma_forward(before[number][a], j)) in range(-5, 5):
                    temp = ewma_forward(before[number][a], j)
                    data[number][a] = temp
                    before[number][a] = temp
                    if set_initial is True:
                        microgear.chat("WebServer", "init," + str(temp))
                    compare(number, dic, data[number][a], a)
                else:
                    if count_reset[number][a] >= 3:
                        set_before[number][a] = True
                        count_reset[number][a] = 0
                    count_reset[number][a] = count_reset[number][a] + 1
Exemplo n.º 19
0
def waterlevel():
    GPIO.output(TRIG, False)
    time.sleep(2)
    GPIO.output(TRIG, True)
    time.sleep(0.00001)
    GPIO.output(TRIG, False)

    while GPIO.input(ECHO) == 0:
        pulse_start = time.time()

    while GPIO.input(ECHO) == 1:
        pulse_end = time.time()

    pulse_duration = pulse_end - pulse_start
    distance = pulse_duration * 17150
    distance = round(distance, 2)

    if distance > 2 and distance < 400:
        print "Water Level:", distance, "cm"
        microgear.chat("WATERLEVEL", distance)
        return distance
    else:
        print "Out Of Range"
Exemplo n.º 20
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)
def subscription(topic, msg):
    global this_role, ready_to_receive, img_status
    ask = msg[2:-1]
    #print(msg)
    if this_role == 'receiver':
        if not ready_to_receive:
            if ask == 'ruok':
                print('Received sender message, sender is ready.')
                netpie.chat(those_name, 'iamok')
                ready_to_receive = True
        else:
            if len(msg) > 1000:
                print("...Receiving image data...")
                print('img len:', len(msg))
                decode_base64(msg, 'test.jpg')  # don't need to save on disk
                print("Image received!")
                print("--------------------------")
                img_status = True

                files = {'file': open('test.jpg', 'rb')}
                url = "http://localhost:5000/uploadImage"
                requests.post(url, files=files)
                print("process is done")
            elif img_status:
                print("...Receiving prediction data...")
                print(msg, len(msg))
                print("Data received!")
                print("==========================")
                print("==========================")
                img_status = False
                ready_to_receive = False
            else:
                ready_to_receive = False
    else:
        print('sdfsdfsf')
        print(topic + ":" + msg)
Exemplo n.º 22
0
def helper(createx=[], setaliasx=[], chatx=[], publishx=[], subscribex=[]):
    print(createx, setaliasx,chatx,publishx,subscribex)

    message = "hello"
    received = False
    if(len(createx) > 0):
        print(microgear.gearkey)
        client.create(createx[0],createx[1],createx[2],{'debugmode': True}) 

    def on_connected():
        print("connect")      
    def on_disconnected():
        print("disconnected") 
    def on_message(topic, message):
        print("message")
        time.sleep(2)
        ack = open(os.path.join(os.getcwd(),"../receiver.txt"), "w")
        print(ack)
        ack.write(message)
        ack.close()
       
    def on_present(gearkey):
        print("present")
    def on_absent(gearkey):
        print("absent")         
    def on_warning(msg):
        print("reject") 
    def on_info(msg):
        print("info")     
    def on_error(msg):
        print("error")  
    
    
    client.on_connect = on_connected
    client.on_disconnect = on_disconnected
    client.on_message = on_message 
    client.on_present = on_present
    client.on_absent = on_absent
    client.on_warning = on_warning
    client.on_info = on_info
    client.on_error = on_error

    if(len(setaliasx) > 0):
        client.setalias(setaliasx[0])
    if(len(subscribex) > 0): 
        client.subscribe(subscribex[0])

    client.resettoken()
    client.connect(False)
    
    if(len(chatx) > 0):
        while True:
            client.chat(chatx[0], message)
            print('chitchat')
            time.sleep(2)

    if(len(publishx) > 0) :
        while True:
            client.publish(publishx[0], message)
            print('pubpush')
            time.sleep(2)
    print("in helper file")
    print(os.path.join(os.getcwd(),"microgear.cache"))
    
    while True:
        pass
Exemplo n.º 23
0
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("Pi")
microgear.on_connect = connection
microgear.on_message = subscription
microgear.on_disconnect = disconnect
microgear.subscribe("/mails")
microgear.connect(False)

status = "OFF"
while True:
    if(microgear.connected):
        if(GPIO.input(5)==0):
            if status == "OFF":
                GPIO.output(3,GPIO.HIGH)
                status = "ON"
                microgear.chat("HTML_web", status)
            else:
                GPIO.output(3,GPIO.LOW)
                status = "OFF"
                microgear.chat("HTML_web", status)
    time.sleep(0.2)

def ActivateCamera():
    # getFromScan = 'Kitkat:P4:8/11/2018:3'
    # add new/remove product
    getFromScan = 'Coke:P4:8/10/2018:75'

    splitString = getFromScan.split(":")
    checkProductName = splitString[0]
    priceOfdata = splitString[1]
    checkExpirydate = splitString[2]
    itemCode = splitString[3]
    # data = {"name": getFromScan}
    data = {
        'price': 30,
        'Code': splitString[3],
        'name': splitString[0],
        'expiryDate': splitString[2],
        'Checkin': str(datetime.now())
    }
    checkDuplicate = False
    counterOuter = 0
    """"""
    # 1.1
    for i in itemlist:

        # 2.1 same product name
        if i['name'] == checkProductName:
            print "have same product name"
            checkDuplicate = True
            # 3.1 same expiryDate
            if i['expiryDate'] == checkExpirydate:
                print "have same expiryDate"

                print i['Code']

                list_of_ItemCode = CreateArrayOfKeyDict(json.dumps(i['Code']))
                list_of_Checkin = CreateArrayOfKeyDict(json.dumps(
                    i['Checkin']))
                counterInner = 0
                for itemID in list_of_ItemCode:

                    print 'U r in the new for loop'
                    # 4.1 itemCode(itemID) is duplicate
                    print 'itemID is ' + itemID
                    print 'itemCode is ' + itemCode
                    if itemID == itemCode:

                        # 5.1 array of Code is equal 1
                        if len(list_of_ItemCode) == 1:
                            # remove statement

                            print 'U are in the code is duplicate condition'

                            checkDuplicate = True
                            removeItemKey = itemlist_key[counterOuter]
                            print removeItemKey
                            forRemoveDupCode = firebase.ref(
                                'CustomerInfo/-KqsdeuVyyatxKELuMs4/Item')
                            forRemoveDupCode.child(removeItemKey).delete()

                            # create new data
                            checkoutData = data = {
                                'price': 30,
                                'Code': itemCode,
                                'name': checkProductName,
                                'expiryDate': checkExpirydate,
                                'Checkin': list_of_Checkin[counterInner],
                                'Checkout': str(datetime.now()),
                                'Province': CustomerAddress
                            }
                            # add to usage database
                            usageItem = firebase.ref('Usage')
                            usageItem.push(checkoutData)

                            itemlist.pop(counterOuter)
                            itemlist_key.pop(counterOuter)

                            print("Successful for removing item" + getFromScan)
                            microgear.chat("outdoor/temp",
                                           json.dumps(itemlist))
                            time.sleep(5)
                            break
                        # 5.2 array of Code is greater than 1
                        else:
                            # delete item code from dict and update
                            # update statement

                            print 'Code  duplicate but length is greater than 1 condition'

                            checkDuplicate = True
                            removeItemKey = itemlist_key[counterOuter]
                            print removeItemKey

                            # update item code
                            list_of_ItemCode.remove(itemID)
                            # getting new values to update data in firebase
                            newCode5 = ReplaceValuesInDict(
                                json.dumps(list_of_ItemCode))
                            # update values in firebase
                            forRemoveExCode = firebase.ref(
                                'CustomerInfo/-KqsdeuVyyatxKELuMs4/Item')
                            forRemoveExCode.child(removeItemKey).child(
                                'Code').set(newCode5)
                            # update local database
                            i['Code'] = UpdateNewValuesDictKey(
                                list_of_ItemCode)

                            # create new data
                            checkoutData = data = {
                                'price': 30,
                                'Code': itemCode,
                                'name': checkProductName,
                                'expiryDate': checkExpirydate,
                                'Checkin': list_of_Checkin[counterInner],
                                'Checkout': str(datetime.now()),
                                'Province': CustomerAddress
                            }
                            # update check in
                            list_of_Checkin.pop(counterInner)
                            updateCheckinValues = ReplaceValuesInDict(
                                json.dumps(list_of_Checkin))
                            forupdateNewCheckin = firebase.ref(
                                'CustomerInfo/-KqsdeuVyyatxKELuMs4/Item')
                            forupdateNewCheckin.child(removeItemKey).child(
                                'Checkin').set(updateCheckinValues)

                            i['Checkin'] = UpdateNewValuesDictKey(
                                list_of_Checkin)

                            # add to usage database

                            usageItem = firebase.ref('Usage')
                            usageItem.push(checkoutData)

                            print("Successful for removing item Code")

                            microgear.chat("outdoor/temp",
                                           json.dumps(itemlist))
                            time.sleep(5)
                            break
                    counterInner += 1
                # 4.2 itemCode(itemID) is not duplicate
                else:
                    # update statement with append new itemCode into existing dict
                    print 'update'
                    checkDuplicate = True
                    removeItemKey = itemlist_key[counterOuter]

                    # update item code
                    # add new code to list
                    list_of_ItemCode.append(itemCode)
                    # getting new values to update data in firebase
                    newCode5 = ReplaceValuesInDict(
                        json.dumps(list_of_ItemCode))
                    # update values in firebase
                    forupdateNewCode = firebase.ref(
                        'CustomerInfo/-KqsdeuVyyatxKELuMs4/Item')
                    forupdateNewCode.child(removeItemKey).child('Code').set(
                        newCode5)
                    # update local database
                    i['Code'] = UpdateNewValuesDictKey(list_of_ItemCode)

                    # update check in
                    # add new check in time to list
                    list_of_Checkin.append(data['Checkin'])
                    # getting new values to update data in firebase
                    newCodeForCheckin = ReplaceValuesInDict(
                        json.dumps(list_of_Checkin))
                    # update values in firebase
                    forupdateNewCheckin = firebase.ref(
                        'CustomerInfo/-KqsdeuVyyatxKELuMs4/Item')
                    forupdateNewCheckin.child(removeItemKey).child(
                        'Checkin').set(newCodeForCheckin)
                    # update local database
                    i['Checkin'] = UpdateNewValuesDictKey(list_of_Checkin)

                    microgear.chat("outdoor/temp", json.dumps(itemlist))
                    time.sleep(5)
                    break

            # 3.2 expiry date is not duplicate
            else:
                # add statement

                foraddnewDate = firebase.ref(
                    'CustomerInfo/-KqsdeuVyyatxKELuMs4/Item')

                NewItemKey = foraddnewDate.push(data)
                print("Successful for adding new date")
                abcd = json.dumps(NewItemKey.values())
                pkpk = re.sub('[^a-zA-Z_0-9-]+', '', abcd)
                itemlist.append(data)
                itemlist_key.append(pkpk)

                microgear.chat("outdoor/temp", json.dumps(itemlist))
                time.sleep(5)
                break
        counterOuter += 1

    # 1.2 if checkDuplicate == false it will add the new one
    if checkDuplicate == False:
        # add statement
        print 'add new item'
        foraddNewitemRef = firebase.ref(
            'CustomerInfo/-KqsdeuVyyatxKELuMs4/Item')

        NewItemKey = foraddNewitemRef.push(data)
        print("Successful for adding new item")
        abcd = json.dumps(NewItemKey.values())
        pkpk = re.sub('[^a-zA-Z_0-9-]+', '', abcd)
        itemlist.append(data)
        itemlist_key.append(pkpk)

        microgear.chat("outdoor/temp", json.dumps(itemlist))
        time.sleep(5)
Exemplo n.º 25
0
microgear.subscribe("/Station_data/3")
microgear.subscribe("/Station_data/4")
microgear.subscribe("/dataControl")
# microgear.subscribe("/web")
os.system('rm microgear.cache')
#client.connect()
microgear.connect()

count_reset = 0
count_Notify = 0
db.APsList()

optimize.findAP()
optimize.findTagRoom()
optimize.findMoTag()
microgear.chat("WebServer", "ready")

while (True):
    # optimize.call_checktime()
    # microgear.publish("/data","test")
    # optimize.trilateration(2.22478863989/5,7.89384797649/5,3.5261/5)
    # optimize.trilateration(5/5,7/5,5/5)
    # send = input("what word to send esp8266:")

    # microgear.chat("client_station",send)

    # ////////////////////////////////////////////////////////////
    # temp = optimize.compare()
    # optimize.resetALL()
    # # print temp
    # if temp[0] != "none":
Exemplo n.º 26
0
import microgear.client as microgear
import time
import logging

appid = "testNetpie"
gearkey = "TYSjnUASnt3xb5s"
gearsecret =  "QJmJp0lXHDavim4KXvHItE8ez"

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

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

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

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

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

while True:
    microgear.chat("testNetpie","Hello world."+str(int(time.time())))
    time.sleep(2)
Exemplo n.º 27
0
def ActivateCamera():
    # set camera
    stream = io.BytesIO()
    with picamera.PiCamera() as camera:
        camera.start_preview(fullscreen=False, window=(1500, 50, 480, 480))
        time.sleep(2)
        camera.capture(stream, format='jpeg')
    # "Rewind" the stream to the beginning so we can read its content
    stream.seek(0)
    pil = Image.open(stream)
    # set scanner
    scanner = zbar.ImageScanner()

    # configure the reader
    scanner.parse_config('enable')

    pil = pil.convert('L')
    width, height = pil.size
    raw = pil.tostring()

    # wrap image data
    image = zbar.Image(width, height, 'Y800', raw)

    # scan the image for barcodes
    scanner.scan(image)
    # reading qr code from image => for item in image
    for symbol in image:
        getFromScan = symbol.data
        # split string
        splitString = getFromScan.split(":")
        # setting data
        checkProductName = splitString[0]
        priceOfdata = splitString[1]
        checkExpirydate = splitString[2]
        itemCode = splitString[3]
        data = {
            'price': splitString[1],
            'Code': splitString[3],
            'name': splitString[0],
            'expiryDate': splitString[2],
            'Checkin': str(datetime.now())
        }
        checkDuplicate = False
        codeDuplicate = False
        counterOuter = 0

        # 1.1 for loop item list
        for item in itemlist:

            # 1.1 duplicate name
            if item['name'] == data['name']:
                checkDuplicate = True

                # 2.1 duplicate date
                if item['expiryDate'] == data['expiryDate']:

                    list_of_ItemCode = createArrayOfKeyDict(
                        json.dumps(item['Code']))
                    list_of_Checkin = createArrayOfKeyDict(
                        json.dumps(item['Checkin']))
                    counterInner = 0
                    for itemID in list_of_ItemCode:

                        # 3.1 duplicate code
                        if itemID == data['Code']:
                            codeDuplicate = True

                            # 4.1 len == 1
                            if len(list_of_ItemCode) == 1:

                                removeItemKey = itemlist_key[counterOuter]
                                print removeItemKey
                                forRemoveDupCode = firebase.ref(
                                    'CustomerInfo/-KqsdeuVyyatxKELuMs4/Item')
                                forRemoveDupCode.child(removeItemKey).delete()
                                checkoutData = {
                                    'price': splitString[1],
                                    'Code': itemCode,
                                    'name': checkProductName,
                                    'expiryDate': checkExpirydate,
                                    'Checkin': list_of_Checkin[counterInner],
                                    'Checkout': str(datetime.now()),
                                    'Province': 'Chiang Mai'
                                }
                                usageItem = firebase.ref('Usage')
                                usageItem.push(checkoutData)

                                itemlist.pop(counterOuter)
                                itemlist_key.pop(counterOuter)
                                microgear.chat("outdoor/temp",
                                               json.dumps(itemlist))
                                time.sleep(5)
                                return True
                            # 4.2 len > 1
                            else:
                                removeItemKey = itemlist_key[counterOuter]
                                print removeItemKey

                                # update item code
                                list_of_ItemCode.remove(itemID)
                                # getting new values to update data in firebase
                                newCode5 = replaceValuesInDict(
                                    json.dumps(list_of_ItemCode))
                                # update values in firebase
                                forRemoveExCode = firebase.ref(
                                    'CustomerInfo/-KqsdeuVyyatxKELuMs4/Item')
                                forRemoveExCode.child(removeItemKey).child(
                                    'Code').set(newCode5)
                                # update local database
                                item['Code'] = updateNewValuesDictKey(
                                    list_of_ItemCode)

                                # create new data
                                checkoutData = {
                                    'price': splitString[1],
                                    'Code': itemCode,
                                    'name': checkProductName,
                                    'expiryDate': checkExpirydate,
                                    'Checkin': list_of_Checkin[counterInner],
                                    'Checkout': str(datetime.now()),
                                    'Province': 'Chiang Mai'
                                }
                                # update check in
                                list_of_Checkin.pop(counterInner)
                                # updateCheckinValues = replaceValuesInDict(json.dumps(list_of_Checkin))
                                forupdateNewCheckin = firebase.ref(
                                    'CustomerInfo/-KqsdeuVyyatxKELuMs4/Item')
                                forupdateNewCheckin.child(removeItemKey).child(
                                    'Checkin').set(updateCheckinValues)

                                item['Checkin'] = updateNewValuesDictKey(
                                    list_of_Checkin)

                                # add to usage database

                                usageItem = firebase.ref('Usage')
                                usageItem.push(checkoutData)
                                microgear.chat("outdoor/temp",
                                               json.dumps(itemlist))
                                time.sleep(5)
                                return True
                        counterInner += 1
                    # 3.2 not duplicate code
                    if codeDuplicate == False:
                        removeItemKey = itemlist_key[counterOuter]

                        # update item code
                        # add new code to list
                        list_of_ItemCode.append(itemCode)
                        # getting new values to update data in firebase
                        newCode5 = replaceValuesInDict(
                            json.dumps(list_of_ItemCode))
                        # update values in firebase
                        forupdateNewCode = firebase.ref(
                            'CustomerInfo/-KqsdeuVyyatxKELuMs4/Item')
                        forupdateNewCode.child(removeItemKey).child(
                            'Code').set(newCode5)
                        # update local database
                        item['Code'] = updateNewValuesDictKey(list_of_ItemCode)

                        # update check in
                        # add new check in time to list
                        list_of_Checkin.append(data['Checkin'])
                        # getting new values to update data in firebase
                        newCodeForCheckin = replaceValuesInDict(
                            json.dumps(list_of_Checkin))
                        # # update values in firebase
                        forupdateNewCheckin = firebase.ref(
                            'CustomerInfo/-KqsdeuVyyatxKELuMs4/Item')
                        forupdateNewCheckin.child(removeItemKey).child(
                            'Checkin').set(newCodeForCheckin)
                        # update local database
                        item['Checkin'] = updateNewValuesDictKey(
                            list_of_Checkin)
                        microgear.chat("outdoor/temp", json.dumps(itemlist))
                        time.sleep(5)
                        return True
                else:
                    foraddnewDate = firebase.ref(
                        'CustomerInfo/-KqsdeuVyyatxKELuMs4/Item')

                    NewItemKey = foraddnewDate.push(data)

                    abcd = json.dumps(NewItemKey.values())
                    pkpk = re.sub('[^a-zA-Z_0-9-]+', '', abcd)
                    itemlist.append(data)
                    itemlist_key.append(pkpk)
                    microgear.chat("outdoor/temp", json.dumps(itemlist))
                    time.sleep(5)
                    return True
            counterOuter += 1

        if checkDuplicate == False:
            foraddNewitemRef = firebase.ref(
                'CustomerInfo/-KqsdeuVyyatxKELuMs4/Item')

            NewItemKey = foraddNewitemRef.push(data)

            abcd = json.dumps(NewItemKey.values())
            pkpk = re.sub('[^a-zA-Z_0-9-]+', '', abcd)
            itemlist.append(data)
            itemlist_key.append(pkpk)
            microgear.chat("outdoor/temp", json.dumps(itemlist))
            time.sleep(5)
def ActivateCamera():
    capture = cv.CaptureFromCAM(0)

    # decalre the zbar_setter as zbar scanner
    zbar_scanner = zbar.ImageScanner()
    checkScan = False;
    while (checkScan == False):
        # create the variable as a frame of camera
        img = cv.QueryFrame(capture)
        height = int(img.height)
        width = int(img.width)

        SubRect = cv.GetSubRect(img, (1, 1, width - 1, height - 1))

        # cv.Rectangle(img,(0,0),(width,height),(255,0,0))

        # to create the image
        set_image = cv.CreateImage((SubRect.width, SubRect.height), cv.IPL_DEPTH_8U, 1)

        cv.ConvertImage(SubRect, set_image)

        image = zbar.Image(set_image.width, set_image.height, 'Y800', set_image.tostring())

        zbar_scanner.scan(image)

        for item in image:

            getFromScan = item.data

            splitString = getFromScan.split(":")
            checkProductName = splitString[0]
            priceOfdata = splitString[1]
            checkExpirydate = splitString[2]
            itemCode = splitString[3]
            
            data = {'price': splitString[1] , 'Code': splitString[3], 'name': splitString[0], 'expiryDate': splitString[2], 'Checkin': str(datetime.now())}
            checkDuplicate = False
            counterOuter = 0
            """"""
            # 1.1
            for i in itemlist:

                # 2.1 same product name
                if i['name'] == checkProductName:
                    print "have same product name"
                    checkDuplicate = True
                    # 3.1 same expiryDate
                    if i['expiryDate'] == checkExpirydate:
                        print "have same expiryDate"
                       
                        print i['Code']
                        list_of_ItemCode = CreateArrayOfKeyDict(json.dumps(i['Code']))
                        list_of_Checkin = CreateArrayOfKeyDict(json.dumps(i['Checkin']))
                        counterInner = 0
                        for itemID in listOfCode:
                            
                            print 'U r in the new for loop'
                            # 4.1 itemCode(itemID) is duplicate
                            print 'itemID is ' + itemID
                            print 'itemCode is ' + itemCode
                            if itemID == itemCode:

                                # 5.1 array of Code is equal 1
                                if len(listOfCode) == 1:
                                    # remove statement

                                    print 'U are in the code is duplicate condition'

                                    checkDuplicate = True
                                    removeItemKey = itemlist_key[counterOuter]
                                    print removeItemKey
                                    forRemoveDupCode = firebase.ref('CustomerInfo/-KqsdeuVyyatxKELuMs4/Item')
                                    forRemoveDupCode.child(removeItemKey).delete()

                                    # create new data
                                    checkoutData = data = {'price': splitString[1], 'Code': itemCode, 'name': checkProductName,
                                                           'expiryDate': checkExpirydate,
                                                           'Checkin': list_of_Checkin[counterInner],
                                                           'Checkout': str(datetime.now()),
                                                           'Province' : 'Chiang Mai'}
                                    # add to usage database
                                    usageItem = firebase.ref('Usage')
                                    usageItem.push(checkoutData)

                                    itemlist.pop(counterOuter)
                                    itemlist_key.pop(counterOuter)

                                    print ("Successful for removing item" + getFromScan)
                                    microgear.chat("outdoor/temp", json.dumps(itemlist))
                                    time.sleep(5)
                                    return True
                                # 5.2 array of Code is greater than 1
                                else:
                                    # delete item code from dict and update
                                    # update statement

                                    print 'Code  duplicate but length is greater than 1 condition'

                                    checkDuplicate = True
                                    removeItemKey = itemlist_key[counterOuter]
                                    print removeItemKey

                                    # update item code
                                    list_of_ItemCode.remove(itemID)
                                    # getting new values to update data in firebase
                                    newCode5 = ReplaceValuesInDict(json.dumps(list_of_ItemCode))
                                    # update values in firebase
                                    forRemoveExCode = firebase.ref('CustomerInfo/-KqsdeuVyyatxKELuMs4/Item')
                                    forRemoveExCode.child(removeItemKey).child('Code').set(newCode5)
                                    # update local database
                                    i['Code'] = UpdateNewValuesDictKey(list_of_ItemCode)

                                    # create new data
                                    checkoutData = data = {'price': splitString[1], 'Code': itemCode, 'name': checkProductName,
                                                           'expiryDate': checkExpirydate, 'Checkin': list_of_Checkin[counterInner],
                                                           'Checkout': str(datetime.now()),
                                                           'Province' : 'Chiang Mai'}
                                    # update check in
                                    list_of_Checkin.pop(counterInner)
                                    updateCheckinValues = ReplaceValuesInDict(json.dumps(list_of_Checkin))
                                    forupdateNewCheckin = firebase.ref('CustomerInfo/-KqsdeuVyyatxKELuMs4/Item')
                                    forupdateNewCheckin.child(removeItemKey).child('Checkin').set(updateCheckinValues)

                                    i['Checkin'] = UpdateNewValuesDictKey(list_of_Checkin)

                                    # add to usage database

                                    usageItem = firebase.ref('Usage')
                                    usageItem.push(checkoutData)

                                    print ("Successful for removing item Code")

                                    microgear.chat("outdoor/temp", json.dumps(itemlist))
                                    time.sleep(5)
                                    return True
                            counterInner += 1
                        # 4.2 itemCode(itemID) is not duplicate
                        else:
                            # update statement with append new itemCode into existing dict
                            print 'update'
                            checkDuplicate = True
                            removeItemKey = itemlist_key[counterOuter]

                            # update item code
                            # add new code to list
                            list_of_ItemCode.append(itemCode)
                            # getting new values to update data in firebase
                            newCode5 = ReplaceValuesInDict(json.dumps(list_of_ItemCode))
                            # update values in firebase
                            forupdateNewCode = firebase.ref('CustomerInfo/-KqsdeuVyyatxKELuMs4/Item')
                            forupdateNewCode.child(removeItemKey).child('Code').set(newCode5)
                            # update local database
                            i['Code'] = UpdateNewValuesDictKey(list_of_ItemCode)

                            # update check in
                            # add new check in time to list
                            list_of_Checkin.append(data['Checkin'])
                            # getting new values to update data in firebase
                            newCodeForCheckin = ReplaceValuesInDict(json.dumps(list_of_Checkin))
                            # update values in firebase
                            forupdateNewCheckin = firebase.ref('CustomerInfo/-KqsdeuVyyatxKELuMs4/Item')
                            forupdateNewCheckin.child(removeItemKey).child('Checkin').set(newCodeForCheckin)
                            # update local database
                            i['Checkin'] = UpdateNewValuesDictKey(list_of_Checkin)

                            microgear.chat("outdoor/temp", json.dumps(itemlist))
                            time.sleep(5)
                            return True


                    # 3.2 expiry date is not duplicate
                    else:
                        # add statement
                        foraddnewDate = firebase.ref('CustomerInfo/-KqsdeuVyyatxKELuMs4/Item')

                        NewItemKey = foraddnewDate.push(data)
                        print("Successful for adding new date")
                        abcd = json.dumps(NewItemKey.values())
                        pkpk = re.sub('[^a-zA-Z_0-9-]+', '', abcd)
                        itemlist.append(data)
                        itemlist_key.append(pkpk)

                        microgear.chat("outdoor/temp", json.dumps(itemlist))
                        time.sleep(5)
                        return True
                counterOuter += 1

            # 1.2 if checkDuplicate == false it will add the new one
            if checkDuplicate == False:
                # add statement
                print 'add new item'
                foraddNewitemRef = firebase.ref('CustomerInfo/-KqsdeuVyyatxKELuMs4/Item')

                NewItemKey = foraddNewitemRef.push(data)
                print("Successful for adding new item")
                abcd = json.dumps(NewItemKey.values())
                pkpk = re.sub('[^a-zA-Z_0-9-]+', '', abcd)
                itemlist.append(data)
                itemlist_key.append(pkpk)

                microgear.chat("outdoor/temp", json.dumps(itemlist))
                time.sleep(5)
                return True

        #cv.ShowImage("ISR Scanner", img)

        # less for fast video rendering
        cv.WaitKey(1)
def Foward_active(sensor1, sensor2, sensor3, SpeedStart, SpeedEnd, timechange,
                  Target):
    if int(sensor2) >= 600:
        motorunit.analogWrite(6, SpeedEnd)
        motorunit.analogWrite(10, SpeedEnd)
        motorunit.analogWrite(4, SpeedEnd)
        motorunit.analogWrite(3, SpeedEnd)
        motorunit.analogWrite(9, 0)
        motorunit.analogWrite(11, 0)
        motorunit.analogWrite(2, 0)
        motorunit.analogWrite(5, 0)

    elif int(sensor2) < 500:
        #Backward part
        motorunit.analogWrite(6, 0)
        motorunit.analogWrite(10, 0)
        motorunit.analogWrite(4, 0)
        motorunit.analogWrite(3, 0)
        motorunit.analogWrite(9, SpeedStart)
        motorunit.analogWrite(11, SpeedStart)
        motorunit.analogWrite(2, SpeedStart)
        motorunit.analogWrite(5, SpeedStart)
        time.sleep(timechange)
        motorunit.analogWrite(6, 0)
        motorunit.analogWrite(10, 0)
        motorunit.analogWrite(4, 0)
        motorunit.analogWrite(3, 0)
        motorunit.analogWrite(9, SpeedEnd)
        motorunit.analogWrite(11, SpeedEnd)
        motorunit.analogWrite(2, SpeedEnd)
        motorunit.analogWrite(5, SpeedEnd)

    if int(sensor1) >= 50:
        motorunit.analogWrite(6, 0)
        motorunit.analogWrite(10, 0)
        motorunit.analogWrite(4, 0)
        motorunit.analogWrite(3, 0)
        motorunit.analogWrite(9, SpeedStart)
        motorunit.analogWrite(11, SpeedStart)
        motorunit.analogWrite(2, SpeedStart)
        motorunit.analogWrite(5, SpeedStart)
    elif int(sensor1) < 50:
        motorunit.analogWrite(6, 0)
        motorunit.analogWrite(10, 0)
        motorunit.analogWrite(4, 0)
        motorunit.analogWrite(3, 0)
        motorunit.analogWrite(9, 0)
        motorunit.analogWrite(11, 0)
        motorunit.analogWrite(2, 0)
        motorunit.analogWrite(5, 0)
    if int(sensor3) >= 600:  # Input the sensor from the main signal source
        motorunit.analogWrite(6, 0)
        motorunit.analogWrite(10, 0)
        motorunit.analogWrite(4, 0)
        motorunit.analogWrite(3, 0)
        motorunit.analogWrite(9, 0)
        motorunit.analogWrite(11, 0)
        motorunit.analogWrite(2, 0)
        motorunit.analogWrite(5, 0)
        time.sleep(14)  # Waiting for the processing OCR data transfer done
        OCRdata = open("OCRdatatransfer.txt", "r")  # Open file and read
        Textout = OCRdata.readline(
        )  # Read from Text and delete too don't forget
        DataOCR = Textout.split(",")  # Data split for the text input function
        Data_1_key = DataOCR[1]  # data key input
        Data_2_value = DataOCR[2]  # data value input
    if int(Data_2_value) == Target:
        microgear.chat("VisualStudio",
                       "Arrived")  # Telling the food is ready to serve
        time.sleep(0.3)
        microgear.chat("VisualStudio", Data_1_key)
        time.sleep(0.3)
        microgear.chat("VisualStudio", Data_2_value)
        time.sleep(0.3)
        motorunit.analogWrite(6, 0)
        motorunit.analogWrite(10, 0)
        motorunit.analogWrite(4, 0)
        motorunit.analogWrite(3, 0)
        motorunit.analogWrite(9, SpeedStart)
        motorunit.analogWrite(11, SpeedStart)
        motorunit.analogWrite(2, SpeedStart)
        motorunit.analogWrite(5, SpeedStart)
        time.sleep(timechange)
        motorunit.analogWrite(6, 0)
        motorunit.analogWrite(10, 0)
        motorunit.analogWrite(4, 0)
        motorunit.analogWrite(3, 0)
        motorunit.analogWrite(9, SpeedEnd)
        motorunit.analogWrite(11, SpeedEnd)
        motorunit.analogWrite(2, SpeedEnd)
        motorunit.analogWrite(5, SpeedEnd)
        time.sleep(5)
    elif int(Data_2_value
             ) != Target:  # Compare the data upto the dataget function
        #Backward part
        motorunit.analogWrite(6, 0)
        motorunit.analogWrite(10, 0)
        motorunit.analogWrite(4, 0)
        motorunit.analogWrite(3, 0)
        motorunit.analogWrite(9, SpeedStart)
        motorunit.analogWrite(11, SpeedStart)
        motorunit.analogWrite(2, SpeedStart)
        motorunit.analogWrite(5, SpeedStart)
        time.sleep(timechange)
        motorunit.analogWrite(6, 0)
        motorunit.analogWrite(10, 0)
        motorunit.analogWrite(4, 0)
        motorunit.analogWrite(3, 0)
        motorunit.analogWrite(9, SpeedEnd)
        motorunit.analogWrite(11, SpeedEnd)
        motorunit.analogWrite(2, SpeedEnd)
        motorunit.analogWrite(5, SpeedEnd)
Exemplo n.º 30
0
   print('Connection lost please connect module1 USB0')
try: 
   ser2 = serial.Serial('/dev/ttyUSB1',115200) # Sensor Elbow 
except:
   print('Connection lost please connect module2 USB1') 
try: 
   ser3 = serial.Serial('/dev/ttyUSB2',115200) # Sensor wrist  
except: 
    print('Connection lost please connect module3 USB2') 
#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

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

def connection():
    print(' ')
def subscription(topic,message):
     print(message)
def disconnect():
    print(' ')

microgear.setalias("VisualStudio")
#microgear.on_connect = connection
microgear.on_message = subscription
microgear.on_disconnect = disconnect
microgear.subscribe("/Topics")
microgear.connect(False)

while True:
        if(microgear.connected):
                microgear.chat("VisualStudio",ser1.readline()+','+ser2.readline()+','+ser3.readline())
Exemplo n.º 31
0
    logging.info("disconnected")


def writefeed():
    data = int(time.time()) % 10
    feeddat = {
        "var1": data,
        "var2": (data - 1) * 10,
        "var3": (data + 5) * 20,
    }
    microgear.writeFeed("feed0001", feeddat, feedkey=netpiefeedkey)


microgear.setalias(aliasmy)
microgear.on_connect = connection
microgear.on_message = subscription
microgear.on_disconnect = disconnect
microgear.subscribe("/mails", qos=0)
microgear.connect(False)

while True:
    if (microgear.connected == False):
        time.sleep(0.5)
        continue

    microgear.chat(aliasmy, "Hello world." + str(int(time.time())))
    microgear.publish('/mails', "Halo")
    writefeed()

    time.sleep(3)
Exemplo n.º 32
0
gearkey = "artG7aZBTy9CSwq"
gearsecret = "D2VSe8wfb5S3IRjls3XOMmC1P"

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):
        check = random.randint(1, 100)
        #print(check)
        microgear.chat("check", check)
    time.sleep(5)
    cam = create_capture(video_src,
                         fallback='synth:bg=../data/lena.jpg:noise=0.05')

    while True:
        ret, img = cam.read()
        gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
        gray = cv.equalizeHist(gray)
        #faces = cascade_fn.detectMultiScale(gray)  # Faces found in gray scale
        t = clock()
        rects = detect(gray, cascade)
        vis = img.copy()
        draw_rects(vis, rects, (0, 255, 0))
        print(type(rects))
        if len(rects) == 0:
            print("No faces found")
            microgear.chat("VisualStudio", "Notfound")
        else:
            print(rects)
            print(rects.shape)
            print("Number of faces detected:" + str(rects.shape[0]))
            microgear.chat("VisualStudio", str(rects.shape[0]))
        if not nested.empty():
            for x1, y1, x2, y2 in rects:
                print("Facedetcted")
                print(int(x1), int(y1))
                print(int(x2), int(y2))
                centre_x = int(x1) + 340
                centre_y = int(y1) + 240
                deg = 2 * math.degrees(
                    math.acos(
                        (int(y1) + 240) / (math.hypot(centre_x, centre_y))))
Exemplo n.º 34
0
            GPIO.output(33, 0)
            GPIO.output(29, 1)
            GPIO.output(31, 1)
        else:
            #not good
            #water pump active
            mood = getmood(2)
            #print('hungry')
            GPIO.output(33, 1)
            GPIO.output(29, 0)
            GPIO.output(31, 1)
            GPIO.output(PUMP_PIN, GPIO.HIGH)
            status = 1
            #print('pump active')
            print('watering')
            microgear.chat("/ldr", sensor)
            time.sleep(5)
            GPIO.output(33, 0)
            GPIO.output(29, 1)
            time.sleep(1)
            GPIO.output(PUMP_PIN, GPIO.LOW)
            status = 0
        print typeof(mo)
        sensor = str(humidity) + ',' + str(temperature) + ',' + str(
            (soil - 200) * 0.222) + ',' + str(
                waterlevel * 0.285) + ',' + str(status) + ',' + mood
        #time.sleep(0.3)
        if (microgear.connected):
            print sensor
            microgear.chat("/ldr", sensor)
Exemplo n.º 35
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)
Exemplo n.º 36
0
def returnChat(message):
	microgear.chat("WebServer",message)
Exemplo n.º 37
0
microgear.on_disconnect = disconnect
microgear.subscribe("/mails")
microgear.connect(False)

GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(4, GPIO.OUT, initial=GPIO.HIGH)

pump_state = 0

while True:
    if GPIO.input(17) == 1:
        # turn leds on
        print "pump on"
        GPIO.output(4, GPIO.LOW)
        pump_state = 1

        sleep(2)  # sleep 1 second

    else:
        # turn leds off
        print "pump off"
        GPIO.output(4, GPIO.HIGH)
        pump_state = 0
        sleep(2)  # sleep 1 second
    if (microgear.connected):
        microgear.chat("sensorstatus", str(int(pump_state)))
        data = {"pump": pump_state * 10}
        #data = {"field1":random.randint(1, 10),"field2":random.randint(1, 10),"field3":random.randint(1, 10)}
        microgear.writeFeed("sobmeoi", data)
Exemplo n.º 38
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.debug("Now I am connected with netpie")

def subscription(topic,message):
    logging.debug(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:
    microgear.chat("doraemon","Hello world."+str(int(time.time())))
    time.sleep(3)
        microgear.chat("outdoor/temp", json.dumps(itemlist))
        time.sleep(5)


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")


if __name__ == "__main__":
    microgear.setalias("MyRaspberryPI")
    microgear.on_connect = connection
    microgear.on_message = subscription
    microgear.on_disconnect = disconnect
    microgear.subscribe("/mails")
    microgear.connect(False)

    if (microgear.connected):
        itemlist, itemlist_key, CustomerAddress = RetreiveData()
        microgear.chat("outdoor/temp", json.dumps(itemlist))
        while True:
            ActivateCamera()
Exemplo n.º 40
0
#client.connect()
microgear.connect()

count_reset = 0
count_Notify = 0
while(True):
	# microgear.publish("/data","test")
	# optimize.trilateration(2.22478863989/5,7.89384797649/5,3.5261/5)
	# optimize.trilateration(5/5,7/5,5/5)
	# send = input("what word to send esp8266:")
	# microgear.chat("esp8266",send)
	# microgear.chat("client_station",send)
	
	temp = optimize.compare()
	optimize.resetALL()
	# print temp
	if temp[0] != "none":
		microgear.chat(temp[0],temp[1])
		if temp[1] == "ON":
			count_Notify = count_Notify +1
			if count_Notify >= 7:
				optimize.Notify_Line()
				count_Notify = 0
		count_reset = 0
	else:
		count_reset = count_reset +1 
		if count_reset > 5:
			optimize.resetALL()
			count_reset = 0
	time.sleep(1)
	
Exemplo n.º 41
0
this_name = 'n3a2'     
those_name = 'n3a1'
this_role = 'sender'
running = True
ready_to_send = False

netpie.setname(this_name)
netpie.on_reject = callback_reject
netpie.on_connect = connection
netpie.on_message = subscription
netpie.on_error = callback_error
netpie.subscribe("/test")
netpie.connect(False) 



if this_role=='sender':
 while not ready_to_send :
  netpie.chat(those_name,'ruok')
  time.sleep(2)
   
 snap_shot = snap()
 b64 = encode_base64(snap_shot)
 netpie.chat(those_name,b64)
 
 time.sleep(2)
else :
 
 while running:
  pass
Exemplo n.º 42
0
def subscription(topic, message):
    print topic + ":" + message

    if message == "RELAY1ON":
        GPIO.output(23, GPIO.LOW)
        microgear.chat("RELAY1STATUS", "ON")

    elif message == "RELAY1OFF":
        GPIO.output(23, GPIO.HIGH)
        microgear.chat("RELAY1STATUS", "OFF")

    elif message == "RELAY2ON":
        microgear.chat("RELAY2STATUS", "ON")
        GPIO.output(24, GPIO.LOW)

    elif message == "RELAY2OFF":
        GPIO.output(24, GPIO.HIGH)
        microgear.chat("RELAY2STATUS", "OFF")

    elif message == "RELAY3ON":
        GPIO.output(25, GPIO.LOW)
        microgear.chat("RELAY3STATUS", "ON")
    elif message == "RELAY3OFF":
        GPIO.output(25, GPIO.HIGH)
        microgear.chat("RELAY3STATUS", "OFF")

    elif message == "RELAY4ON":
        GPIO.output(8, GPIO.LOW)
        microgear.chat("RELAY4STATUS", "ON")
    else:
        GPIO.output(8, GPIO.HIGH)
        microgear.chat("RELAY4STATUS", "OFF")