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)
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 + "/&")
def settingStandard(payload): mosStd = "mosStd" #moisture standard tmpStd = "tmpStd" #temp standard ligStd = "ligStd" #light standard #errorCode 0: database error # 1: water not flows # 2: water not true arare # 3: temp not decrease after shower # 4: not time to shower # 5: slat is opened # 6: slat is closed # 7: light value not decrease objecStan = json.loads(payload) for i in objecStan: print(" - key: "+str(i)) print(" - value: "+str(objecStan[i])) print(" ---------------------") if(i == mosStd): sp.put(mosStd,objecStan[i]) elif(i == tmpStd): sp.put(tmpStd,objecStan[i]) elif(i == ligStd): sp.put(ligStd,objecStan[i]) if(isConnect()): response = json.dumps({"topic":"settingStandard","success":True,"message":payload}) microgear.publish("/response",str(response))
def main1(): while True: #DHT22 Sensor Reading humidity, temperature = Adafruit_DHT.read_retry(sensor, DHT_Sensor) #print("Temp={0:0.1f}*C Humidity={1:0.1f}%".format(temperature, humidity)) microgear.publish("/outdoor/temp", int(temperature)) microgear.publish("/outdoor/hud", int(humidity)) #Button Reading button_state = GPIO.input(button) if button_state == False: print('Button Pressed...') #Run Capture File os.system('python capture.py') #Send Image to Line file = { 'message': (None, "Someone has press the button"), 'imageFile': open('/home/pi/Pic1/Image.png', 'r+b') } url = 'https://notify-api.line.me/api/notify' token = 'f2tilnNiJDmTacnp4Xa7njNCZmppUckraZR071Aiw4Z' headers = {'Authorization': 'Bearer ' + token} res = requests.post(url, headers=headers, files=file) print(res.text) os.remove('/home/pi/Pic1/Image.png') time.sleep(1) #Starting Face_Recognition os.system( 'python pi_face_recognition.py --cascade haarcascade_frontalface_default.xml --encodings encodings.pickle' ) time.sleep(0.2)
def httpRequest(): '''Function to send the POST request to ThingSpeak channel for bulk update.''' # global messageBuffer global url global fields global _temperature # data = json.dumps({'write_api_key':writeAPIkey,'updates':messageBuffer}) # Format the json data buffer url_req = url + fields print(url_req) req = urllib.request.Request(url=url_req) # requestHeaders = {"User-Agent":"mw.doc.bulk-update (Raspberry Pi)","Content-Type":"application/json","Content-Length":str(len(data))} # for key,val in requestHeaders.items(): # Set the headers # req.add_header(key,val) ## req.add_data(data) # Add the data to the request # req.data = data.encode("utf-8") # print(req.data) # Make the request to ThingSpeak try: response = urllib.request.urlopen(req) # Make the request print(response.getcode() ) # A 202 indicates that the server has accepted the request print('sending data to netpie\n') microgear.publish("/brew/temperature", _temperature, {'retain': True}) except urllib.request.HTTPError as e: print(e.code) # Print the error code # messageBuffer = [] # Reinitialize the message buffer global lastConnectionTime lastConnectionTime = time.time() # Update the connection time
def publishRawData(payload,fq,timeStamp): if(isConnect()): print("Microgear, publish Data to netpie") microgear.publish("/rawData",str(payload),{'retain':True}) return True,int(int(timeStamp)+(int(fq)*int(minuteStamp))) #return result and next time to publish data else: print("Microgear, Exception!! microgear not connect") return False,0 #return false
def onRefreshRawData(): mosObj = json.loads(inputs.getMoistureObject()) temObj = json.loads(inputs.getTempObject()) ligObj = json.loads(inputs.getLightObject()) timeStamp = int(time.time()) payload = "{\"time\":"+str(timeStamp)+",\"moisture\":"+str(json.dumps(mosObj))+",\"temp\":"+str(json.dumps(temObj)+",\"light\":"+str(json.dumps(ligObj)))+"}" microgear.publish("/rawData",str(payload),{'retain':True})
def publisLogDataList(): if(isConnect()): print("Microgear, publish History List to netpie") result, data = db.selectLogDataList() if(result): microgear.publish("/logDataList",str(data),{'retain':True}) microgear.publish("/hasLogList","1") else: print("Microgear, Exception!! microgear not connect")
def speak(audioString): print(audioString) microgear.publish('/speech',audioString) tts = gTTS(text=audioString, lang='en') fileName = str(time.time()) + ".mp3" tts.save(fileName) os.system("mpg321 " + fileName) playsound.playsound(fileName,True) #playsound(fileName,True) os.remove(fileName)
def publishImage(fq,timeStamp): #frequency in hour unit if(isConnect()): print("Microgear, publish Image to netpie") inputs.captureImage() microgear.publish("/photo",str(timeStamp)+","+str(inputs.cvIM2Base64()),{'retain':True}) microgear.publish("/hasPhoto","1") #publish to app for load image return True,int(int(timeStamp)+(int(fq)*int(hourStamp))) #retuen result and next time to publis image else: print("Microgear, Exception!! microgear not connect") return False,0 #return false
def subscription(topic, message): print message global status if message == "ON": GPIO.output(PUMP_PIN, GPIO.HIGH) status = 1 else: GPIO.output(PUMP_PIN, GPIO.LOW) status = 0 logging.info(topic + "-- " + status) microgear.publish("/gearname/ldr", status)
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 settingDetails(payload): fqPData = "fqPData" #frequency to publish data to netpie fqPImage = "fqPImage" #frequency to publish image to netpie fqIData = "fqIData" #frequency to insert data to database fqShower = "fqShower" #frequency to shower (0 = auto, > 0 = user setting) ageData = "ageData" #day off store data in database autoMode = "autoMode" #auto mode lastUpdate = "lastUpdate" objDetails = json.loads(payload) if(int(objDetails[lastUpdate]) > int(sp.get(lastUpdate))): global hasReload hasReload = True for i in objDetails: print(" - key: "+str(i)) print(" - value: "+str(objDetails[i])) print(" ---------------------") if(i == fqPData ): sp.put(fqPData,objDetails[i]) elif(i== fqPImage): sp.put(fqPImage,objDetails[i]) elif(i== fqIData): sp.put( fqIData,objDetails[i]) elif(i == fqShower): sp.put(fqShower,objDetails[i]) elif(i == ageData): sp.put(ageData,objDetails[i]) elif(i== autoMode): sp.put(autoMode,objDetails[i]) elif(i == lastUpdate): sp.put(lastUpdate,objDetails[i]) if(isConnect()): response = json.dumps({"topic":"settingDetails","success":True,"message":payload}) microgear.publish("/response",str(response))
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)
def update_table_2(self, info): # TODO : Argent Require horHeaders = ['Prediction', 'Confident (%)'] ind = 0 # self.tableWidget.resizeColumnsToContents() # self.tableWidget.resizeRowsToContents() self.tableWidget.setColumnCount(2) self.tableWidget.setRowCount(len(info.keys())) self.tableWidget.setColumnWidth(0, 400) self.tableWidget.setColumnWidth(1, 142) for k, v in info.items(): KeyItem = QTableWidgetItem(k) ValItem = QTableWidgetItem(str(v*100)) self.tableWidget.setItem(ind, 0, KeyItem) self.tableWidget.setItem(ind, 1, ValItem) ind += 1 self.tableWidget.setHorizontalHeaderLabels(horHeaders) # TODO : Stuff for netpie client.publish('/risk', str(v*100)) client.publish('/risk_lb', str(k)) filestuff = self.img_tmp img = str(filestuff[0]) with open(img,'rb') as img_file : encoded_string = base64.b64encode(img_file.read()) img_file.close() str_img = str('<center><img src="data:image/png;base64,' + encoded_string.decode( 'utf-8') + '" width="300" height="300"/><center>') client.publish('/snap', str_img)
def onRefresh(): mosObj = json.loads(inputs.getMoistureObject()) temObj = json.loads(inputs.getTempObject()) ligObj = json.loads(inputs.getLightObject()) timeStamp = int(time.time()) payload = "{\"time\":"+str(timeStamp)+",\"moisture\":"+str(json.dumps(mosObj))+",\"temp\":"+str(json.dumps(temObj)+",\"light\":"+str(json.dumps(ligObj)))+"}" microgear.publish("/rawData",str(payload),{'retain':True}) response = json.dumps({"topic":"refresh","success":True,"message":""}) microgear.publish("/response",str(response)) inputs.captureImage() microgear.publish("/photo",str(timeStamp)+","+str(inputs.cvIM2Base64()),{'retain':True}) microgear.publish("/hasPhoto","1") #publish to app for load image
def refreshImage(): if(isConnect()): print("Microgear, publish Image to netpie") inputs.captureImage() microgear.publish("/photo",str(timeStamp)+","+str(inputs.cvIM2Base64()),{'retain':True}) microgear.publish("/hasPhoto","1") #publish to app for load image response = json.dumps({"topic":"refreshIM","success":True,"message":payload}) microgear.publish("/response",str(response))
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 controlsDevices(payload): success = False message = "" response = None if(payload == 1): print(" Water from user command") mosObj = json.loads(inputs.getMoistureObject()) if(ctrl.water()): time.sleep(10) #wait 10 second newMosObj = json.loads(inputs.getMoistureObject()) print(" old moisture: "+str(mosObj["average"])) print(" new moisture: "+str(newMosObj["average"])) if((float(newMosObj["average"]-float(mosObj["average"])>5))):# if moisture value more than valus before onRefreshRawData() result = db.insertLogData(int(time.time()),1,2,float(mosObj["average"]),float(newMosObj["average"])) #insert log to database if(result): print(" All success") success = True message = json.dumps({"working":payload,"valBefore":float(mosObj["average"]),"valAfter":float(newMosObj["average"])}) publisLogDataList() else: message = json.dumps({"errorCode":0,"msg":"database error","working":payload,"valBefore":float(mosObj["average"]),"valAfter":float(newMosObj["average"])}) else: if((float(newMosObj["average"])>float(mosObj["average"]))>=1): message = json.dumps({"errorCode":8,"working":payload,"valBefore":float(mosObj["average"]),"valAfter":float(newMosObj["average"])}) publisLogDataList() else: print(" Error! water not true Arare") message = json.dumps({"working":payload,"errorCode":2,"msg":"water not true arare"}) else: print(" Error! water not flows") message = json.dumps({"working":payload,"errorCode":1,"msg":"water not flows"}) elif(payload == 2): print(" Shower from user command") fqShower = "fqShower" #frequency to shower (0 = auto, > 0 = user setting) timeStamp = int(time.time()) lastTimeShower = sp.get("lastTimeShower") print("lastTimeShower: "+str(lastTimeShower)) minStamp = 60 m = "" fq = sp.get(fqShower) if(fq == 0): fq = t.getFqShower()#get ferquency from system (fq in minute *60) minStamp if(int(timeStamp)>=(int(lastTimeShower)+(int(fq)*int(minStamp)))): temObj = json.loads(inputs.getTempObject()) if(ctrl.shower()): time.sleep(10) newTemObj = json.loads(inputs.getTempObject()) print(" old temp: "+str(temObj["average"])) print(" new temp: "+str(newTemObj["average"])) if(float(newTemObj["average"])<=float(temObj["average"])): onRefreshRawData() result = db.insertLogData(timeStamp,2,2,float(temObj["average"]),float(newTemObj["average"])) #insert log to database if(result): success = True message = json.dumps({"working":payload,"valBefore":float(temObj["average"]),"valAfter":float(newTemObj["average"])}) print(" All success") publisLogDataList() sp.put("lastTimeShower",timeStamp) else: message = json.dumps({"errorCode":0,"msg":"database error","working":payload,"valBefore":float(temObj["average"]),"valAfter":float(newTemObj["average"])}) else: print(" Error! temp not decrease after shower") message = json.dumps({"working":payload,"errorCode":3,"msg":"temp not decrease after shower"}) else: print(" Error! water not flows") message = json.dumps({"working":payload,"errorCode":1,"msg":"water not flows"}) else: nextTime = (int(lastTimeShower)+(int(fq)*int(minStamp))) print(" not time to shower, Working again at "+str(t.timeStampToDateTime(nextTime))) message = json.dumps({"working":payload,"errorCode":4,"msg":str(nextTime)}) elif(payload == 3): print(" Open slat from user command") slatStatus = sp.get("slatStatus") #status of slat print(" slatStatus: " +str(slatStatus)) if(int(slatStatus) != 1): ligObj = json.loads(inputs.getLightObject()) if(ctrl.openSlat()):#if can open slat time.sleep(10) newLigObj = json.loads(inputs.getLightObject()) sp.put("slatStatus",str("1")) publisSlatStatus(1) result = db.insertLogData(int(time.time()),3,2,float(ligObj["light_in"]),float(newLigObj["light_in"])) #insert log to database onRefreshRawData() if(result): publisLogDataList() success = True message = json.dumps({"working":payload,"valBefore":float(ligObj["light_in"]),"valAfter":float(newLigObj["light_in"])}) print(" All success") else: message = json.dumps({"errorCode":0,"msg":"database error","working":payload,"valBefore":float(ligObj["light_in"]),"valAfter":float(newLigObj["light_in"])}) else: print(" slat is opened (1)") message = json.dumps({"working":payload,"errorCode":5,"msg":"slat is opened"}) elif(payload == 4): print(" Close slat from user command") slatStatus = sp.get("slatStatus") #status of slat print(" slatStatus: " +str(slatStatus)) if(int(slatStatus) != 0): ligObj = json.loads(inputs.getLightObject()) if(ctrl.closeSlat()): #if can close slat time.sleep(10) newLigObj = json.loads(inputs.getLightObject()) print(" old light: "+str(ligObj["light_in"])) print(" new light: "+str(newLigObj["light_in"])) sp.put("slatStatus",str("0")) publisSlatStatus(0) result = db.insertLogData(int(time.time()),4,2,float(ligObj["light_in"]),float(newLigObj["light_in"])) #insert log to database onRefreshRawData() if(result): publisLogDataList() else: message = json.dumps({"errorCode":0,"msg":"database error","working":payload,"valBefore":float(ligObj["light_in"]),"valAfter":float(newLigObj["light_in"])}) if(float(newLigObj["light_in"]) < float(ligObj["light_in"])): success = True message = json.dumps({"working":payload,"valBefore":float(ligObj["light_in"]),"valAfter":float(newLigObj["light_in"])}) else: print(" new light value not decrease") message = json.dumps({"working":payload,"errorCode":7,"msg":"light value not decrease"}) else: print(" slat is closed (0)") message = json.dumps({"working":payload,"errorCode":6,"msg":"slat is closed"}) response = json.dumps({"topic":"controlDevices","success":success,"message":message}) #print("response: "+str(response)) if(isConnect()): microgear.publish("/response",str(response))
def publisSlatStatus(slatStatus): # 0 is close, 1 is open if(isConnect()): microgear.publish("/slatStatus",str(slatStatus),{'retain':True}) print("Microgear, publish Slat Status ("+str(slatStatus) +") to netpie") else: print("Microgear, Exception!! microgear not connect")
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
print "Now I am connected with netpie" def subscription(topic, message): print topic + "=" + message if topic == "/PudzaSOI/test_cmd": print "Recv:" + message def disconnect(): print "disconnect is work" microgear.setalias("test") microgear.on_connect = connection microgear.on_message = subscription microgear.on_disconnect = disconnect microgear.subscribe("/test_data") microgear.subscribe("/test_cmd") microgear.connect(False) i = 0 while True: i = i + 1 d = 't=' + str(i) + ',ec=' + str(i + 1) + ',' + str(i + 2) + ',ph=' + str(i + 3) microgear.publish("/test_data", d, {"retain": True}) time.sleep(1)
if args["video"] is None : camera = VideoStream(src=0, usePiCamera=True, resolution=frameSize, framerate=32).start() else : camera = cv2.VideoCapture(args["video"]) time.sleep(2.0) this_name = 'CAMERA' microgear.setname(this_name) microgear.on_reject = callback_reject microgear.on_connect = connection microgear.on_message = subscription microgear.on_error = callback_error microgear.connect(False) microgear.publish("/countPeople",countPeople) # Get the next frame. while True: # If using a webcam instead of the Pi Camera, if args["video"] is None : Frame = camera.read() # If using a video file else: _,Frame = camera.read() # cannot fetch Frame if (Frame is None): break Frame = imutils.resize(Frame, width=frameSize[0]) # cannot fetch Frame if (Frame is None) : break
def subscription(topic,msg): if msg == "b'?'": microgear.publish("/countPeople",countPeople)
microgear.subscribe("/uno/amptemp"); microgear.subscribe("/uno/amphum"); microgear.subscribe("/uno/wtrtemp"); microgear.subscribe("/uno/flow"); microgear.subscribe("/uno/soilhum"); microgear.subscribe("/uno/rain"); microgear.subscribe("/uno/ec"); microgear.connect(False) while True: msg = ser.readline() # print msg # microgear.chat("htmlgear",msg) datalist = msg.split(',') if len(datalist) == 7: microgear.publish("/uno/amptemp",datalist[0]) microgear.publish("/uno/amphum",datalist[1]) microgear.publish("/uno/wtrtemp",datalist[2]) microgear.publish("/uno/soilhum",datalist[3]) microgear.publish("/uno/rain",datalist[4]) microgear.publish("/uno/flow",datalist[5]) microgear.publish("/uno/ec",datalist[6]) elif msg.find(',') == -1: print msg microgear.publish("/eccalmsg",msg) time.sleep(2)
import sys if len(sys.argv) > 1: # NETPIE appid and apikeys appid = "SKHOME" gearkey = "VXM0JO7qieJFU4u" gearsecret = "tB9D6qn9poYC2FEgFexxjMIDD" microgear.create(gearkey, gearsecret, appid, {'debugmode': False}) def connection(): print "Now I am connected with netpie" def subscription(topic, message): print topic + "=" + message def disconnect(): print "disconnect is work" microgear.setalias("strw_test") microgear.on_connect = connection microgear.on_message = subscription microgear.on_disconnect = disconnect microgear.subscribe("/strawberry_watering") microgear.connect(False) delaytime = sys.argv[1] microgear.publish("/strawberry_watering", delaytime) else: print "Please enter delay time.!!"
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("Pi") microgear.on_connect = connection microgear.on_message = subscription microgear.on_disconnect = disconnect #microgear.subscribe("/ldr") microgear.connect(False) count = 0 while True: if (microgear.connected): microgear.publish("/ldr", str(count)) print count count = count + 10 time.sleep(1)
msg = ser.readline() datalist = msg.split(',') # print msg if len(datalist) == 4: temp = datalist[0] ec = datalist[1] x = datalist[2] ph = datalist[3].rstrip() X = float(x) tub = -1120.4 * X * X + 5742.3 * X - 4352.9 # if tub < 0: # tub = 0 # sim.......... # ph = '7.9' #............... datastr = temp + ',' + ec + ',' + "%.2f" % X + ',' + ph microgear.publish("/data", datastr) relaystatus = str(GPIO.input(relays[0])) + ',' relaystatus += str(GPIO.input(relays[1])) + ',' relaystatus += str(GPIO.input(relays[2])) time.sleep(1) # microgear.chat("web", relaystatus) else: microgear.publish("/eccalmsg", msg) time.sleep(2)
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)
def onSaveClock(payload): alarmSet = json.loads(payload) alarmClock.setAlarmToText(alarmSet) response = json.dumps({"topic":"alarm","success":True,"message":payload}) microgear.publish("/response",str(response))
microgear.subscribe("/uno/rain") microgear.subscribe("/uno/ec") microgear.subscribe("/reporter") microgear.subscribe("/sptemp") microgear.subscribe("/sptempf") microgear.subscribe("/tempauto") microgear.connect(False) alrain = 1 almistSta = 1 while True: y, m, d, h, mi, s, wd, wy, isd = time.localtime() if s % 15 == 0: microgear.publish("/reporter", 'O') payload = { 'api_key': api_key, 'field1': amptemp, 'field2': amphum, 'field3': str(wtrtemp), 'field4': str(soilhum), 'field5': str(rain), 'field6': str(flow), 'field7': str(ec), 'field8': str(lux) } r = requests.post(urlThingspeak, params=payload, verify=False) # print r.text
def publis(topic,payload): if(isConnect()): print("Microgear, publish topic: "+str(topic)+" to netpie") microgear.publish(str("/"+topic),str(payload)) else: print("Microgear, Exception!! microgear not connect")
def disconnect(): logging.info("disconnected") microgear.setalias("5735451") microgear.on_connect = connection microgear.on_message = subscription microgear.on_disconnect = disconnect microgear.connect() while True: db = pymysql.connect("localhost", "root", "009564", "Status") cursor = db.cursor() sql = "SELECT ec, ph FROM ecphCurrent WHERE id=1" try: cursor.execute(sql) result = cursor.fetchone() value = result[0] otherValue = result[1] except: value = 0.0 otherValue = 0.0 result = (str(value) + "," + str(otherValue)) microgear.publish("/status/5735451", result) logging.info(result) time.sleep(4)
rset = True else: rset = False GPIO.output(relays[int(message[0])], rset) def disconnect(): print "disconnect is work" microgear.setalias("PCU1") microgear.on_connect = connection microgear.on_message = subscription microgear.on_disconnect = disconnect microgear.subscribe("/msg"); microgear.subscribe("/cmd"); microgear.connect(False) while True: y,m,d,h,mi,s,wd,wy,isd = time.localtime() msg = ser.readline() datalist = msg.split(',') if len(datalist) == 3: temp = datalist[0] hh = datalist[1] ec = datalist[2].rstrip() data = {"ec": ec ,"temp":temp} microgear.writeFeed("MelonFeed",data) microgear.publish("/msg",msg) time.sleep(1)