Пример #1
0
def setup_aws_shadow_client(host, rootCAPath, privateKeyPath, certificatePath, device_name):
    # Configure logging
    logger = logging.getLogger("AWSIoTPythonSDK.core")
    logger.setLevel(logging.INFO)
    streamHandler = logging.StreamHandler()
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    streamHandler.setFormatter(formatter)
    logger.addHandler(streamHandler)

    # Init AWSIoTMQTTShadowClient
    shadow = AWSIoTMQTTShadowClient(device_name + "-client")
    shadow.configureEndpoint(host, 8883)
    shadow.configureCredentials(rootCAPath, privateKeyPath, certificatePath)

    # AWSIoTMQTTShadowClient configuration
    shadow.configureAutoReconnectBackoffTime(1, 32, 20)
    shadow.configureConnectDisconnectTimeout(10)  # 10 sec
    shadow.configureMQTTOperationTimeout(5)  # 5 sec

    #Last Will
    shadow.configureLastWill('my/things/' + device_name + '/update', '{"state":{"reported":{"connected":"false"}}}', 1)

    # Connect to AWS IoT
    shadow.connect()

    # Create a deviceShadow with persistent subscription
    client = shadow.createShadowHandlerWithName(device_name, True)

    return shadow, client
# Connect and subscribe to AWS IoT
myAWSIoTMQTTClient.connect()
if args.mode == 'both' or args.mode == 'subscribe':
    myAWSIoTMQTTClient.subscribe(topic, 1, customCallback)
time.sleep(2)

def myShadowUpdateCallback(payload, responseStatus, token):
	print()
	print('UPDATE: $aws/things/' + SHADOW_HANDLER +
	'/shadow/update/#')
	print("payload = " + payload)
	print("responseStatus = " + responseStatus)
	print("token = " + token)
# Create, configure, and connect a shadow client.
myShadowClient = AWSIoTMQTTShadowClient(SHADOW_CLIENT)
myShadowClient.configureEndpoint(HOST_NAME, 8883)
myShadowClient.configureCredentials(ROOT_CA, PRIVATE_KEY,
CERT_FILE)
myShadowClient.configureConnectDisconnectTimeout(10)
myShadowClient.configureMQTTOperationTimeout(5)
myShadowClient.connect()
# Create a programmatic representation of the shadow.
myDeviceShadow = myShadowClient.createShadowHandlerWithName(
SHADOW_HANDLER, True)


#############ENVIAR NOTIFICACION POR CORREO#################
# Publish to the same topic in a loop
loopCount = 0
for i in range (0,10):
    if args.mode == 'both' or args.mode == 'publish':
Пример #3
0
class ThermoApp(App):
	DEVICE = '/dev/ttyAMA0'
	BAUD = 9600
	TIMEOUT = 5
	ipaddr=''
	lastGPUTempRead=0.0
	lastWeatherRead=0.0
	lastTempPressHumidRead=0.0
	lastShadowUpdate=0.0
	lastSetAlerts=0.0
	ui = ObjectProperty(None)
	zones = ObjectProperty(None)
	zonemap=['','17','27','22']
	zoneData={
		'1':ThermoZone(1,17),
		'2':ThermoZone(2,27),
		'3':ThermoZone(3,22)
	}
	furnace=Furnace()
	currentZone=1
	dataFeed = deque()
	
	deviceData={
		'AA':ThermoDevice('AA',2,'master'),
		'AB':ThermoDevice('AB',2,'tess'),
		'AC':ThermoDevice('AC',2,'kate'),
		'AD':ThermoDevice('AD',3,'girls'),
		'AE':ThermoDevice('AE',1,'snug'),
		'AF':ThermoDevice('AF',1,'living'),
		'AG':ThermoDevice('AG',0,'porch'),
		'AH':ThermoDevice('AH',1,'ground'),
		'BM':ThermoDevice('BM',0,'thermo'),
		'AW':ThermoDevice('AW',0,'weather'),
		'PI':ThermoDevice('PI',0,'GPU')}
	ser = serial.Serial(DEVICE, BAUD)
	
	voltage = 0.0
	tempvale = 0.0
	pressure = 0.0
	weather = []
	sensor = BME280(mode=BME280_OSAMPLE_8)
	host='a2pveb84akyryv.iot.us-east-1.amazonaws.com'
	rootCAPath='rootca.key'
	privateKeyPath='bdca28f300.private.key'
	certificatePath='bdca28f300.cert.pem'
	# -e a2pveb84akyryv.iot.us-east-1.amazonaws.com -r rootca.key -c bdca28f300.cert.pem -k bdca28f300.private.key

	def show_config(self):
		App.open_settings(self)
		Window.request_keyboard(self.keyboard_close, self)
	
	def keyboard_close(self):
		#print "close"
		return

	def build_config(self, config):
		config.setdefaults('startup', {
	    		'weatherText': 'foobar',
	    		'picSource': 'weather/1.jpg'
		})
		self.config=config

	def build_settings(self, settings):
		jsondata = """[
			{ "type": "title",
			"title": "Thermo application" },
			{ "type": "options",
			"title": "Initial Weather",
			"desc": "Weather Pic",
			"section": "startup",
			"key": "picSource",
			"options": ["weather/1.jpg", "weather/images.jpg", "weather/part_coudy.jpg"] },
			{ "type": "string",
			"title": "Weather Title",
			"desc": "Weather Text",
			"section": "startup",
			"key": "weatherText" }]"""
		settings.add_json_panel('Thermo application', self.config, data=jsondata)

	def build(self):
		self.ui=ThermoWidget()
		self.ui.weatherText='ThermoWidget'
		self.ui.picSource='weather/1.jpg'
		self.ui.tempDataText="temps"
		self.ui.setPointText="0.0"
		self.ui.ipAddressText="192.168.0.0"
		self.ui.averageTempText="0.0"
		self.ui.zoneAlertsText="Loading..."
		btn=self.ui.ids['increase']
		btn.bind(on_release=self.increaseSetPoint)
		btn=self.ui.ids['decrease']
		btn.bind(on_release=self.decreaseSetPoint)
		self.zones=self.ui.ids['zones']
		for z in range(0,4):
			btnstate='down' if self.currentZone==z else 'normal'
			btn = ToggleButton(
				allow_no_selection=False,
				text=str(z), 
				group='zonegroup', 
				size_hint=(None, None),
				halign='center',
				state=btnstate,
				background_normal='normal.png',
				background_down='down.png')
    			btn.bind(on_release=self.switch_zone)
    			self.zones.add_widget(btn)
		self.ui.weatherText=self.config.get('startup', 'weatherText')
		temp = subprocess.check_output(["ifconfig","wlan0"],universal_newlines=True)
		pos1=temp.find("inet addr:")
		pos2=temp.find(" Bcast:")
		self.ui.ipAddressText=temp[pos1+10:pos2]
		self.connectMQTT()
		Clock.schedule_interval(self.mainLoop, 10.0)
		return self.ui

	def switch_zone(self,toggle):
		self.currentZone=int(toggle.text)
		self.updateDisplay()
		pass

	def increaseSetPoint(self,instance):
		self.zoneData[str(self.currentZone)].setPoint+=5.0/9.0
		self.takeAction()
		self.updateDisplay()
		pass

	def decreaseSetPoint(self,instance):
		self.zoneData[str(self.currentZone)].setPoint-=5.0/9.0
		self.takeAction()
		self.updateDisplay()
		pass

	def loadConfig(self):
		# read config file into memory vars
		return

	def avgZone(self,zonenum):
		tot=0.0
		cnt=0
		for i in self.deviceData:
			device=self.deviceData[i]
			if(device.zone==zonenum):
				tot+=float(device.temp)
				if(device.temp>0.0):
					cnt+=1
		if cnt==0:
			cnt=1
		return tot/cnt
	
	def connectMQTT(self):
		self.myShadowClient = AWSIoTMQTTShadowClient("thermo")
    		#self.myAWSIoTMQTTClient = AWSIoTMQTTClient("thermo")

		self.myShadowClient.configureEndpoint(self.host, 8883)
		self.myShadowClient.configureCredentials(self.rootCAPath, self.privateKeyPath, self.certificatePath)

		# myShadowClient connection configuration
		self.myShadowClient.configureAutoReconnectBackoffTime(1, 32, 20)
		
		self.myShadowClient.connect()

		self.myAWSIoTMQTTClient = self.myShadowClient.getMQTTConnection()
		self.myAWSIoTMQTTClient.configureOfflinePublishQueueing(-1)  # Infinite offline Publish queueing
		self.myAWSIoTMQTTClient.configureDrainingFrequency(2)  # Draining: 2 Hz
		self.myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10)  # 10 sec
		self.myAWSIoTMQTTClient.configureMQTTOperationTimeout(5)  # 5 sec
		

		# Connect and subscribe to AWS IoT
		#self.myAWSIoTMQTTClient.connect()
		# myAWSIoTMQTTClient.subscribe("thermo", 1, customCallback)
		# self.myAWSIoTMQTTClient.publish("thermo", "[[\'"+(strftime(DATE_FORMAT,localtime())+"\','TT','START','1']]", 1)
		# Create a device shadow instance using persistent subscription
		self.myDeviceShadow = self.myShadowClient.createShadowHandlerWithName("mythermo", True)
		return

	def updateDeviceShadow(self):
		if(time()-self.lastShadowUpdate > 300):
			thingState={
				"state" : {
					"reported" : {
						"sensors" : {
						},
						"zones" : {
						},
						"furnace" : {
						}
					}
				}
			}
			for i in self.deviceData:
				device=self.deviceData[i]
				thingState["state"]["reported"]["sensors"][device.id]={"temp":tformat(device.temp),"location":device.location,"batt":device.batt,"alert":device.alert,"lastupdate":device.lastupdate,"press":device.press,"humid":device.humid}
			for i in self.zoneData:
    				zone=self.zoneData[i]
				thingState["state"]["reported"]["zones"][zone.id]={"status":zone.status, "average":tformat(zone.average), "setPoint":tformat(zone.setPoint), "triggertemp":tformat(zone.triggertemp), "alert":zone.alert}
			thingState["state"]["reported"]["furnace"]={"onSeconds":self.furnace.onSeconds,"offSeconds":self.furnace.offSeconds,"maxBurnSeconds":self.furnace.maxBurnSeconds,"maxRestSeconds":self.furnace.maxRestSeconds,"status":self.furnace.status,"lastupdate":self.furnace.lastupdate}
			self.myDeviceShadow.shadowUpdate(json.dumps(thingState), None, 5)
			self.lastShadowUpdate=time()
		return	
		
	def updateDisplay(self):
		# draw everything
		# if click then show subpanel or change config
		self.ui.setPointText="{:2.0f}".format(self.zoneData[str(self.currentZone)].setPoint*9/5+32.0)
		self.ui.averageTempText=tformat(self.avgZone(self.currentZone))
		self.ui.tempDataText=''
		zonealerts='Alerts:'
		for i in self.deviceData:
			device=self.deviceData[i]
			thisDeviceText=tformat(device.temp)
			thisDeviceText+=" "+device.location+" "+device.alert
			self.ui.tempDataText+=thisDeviceText+'\n'
		for i in self.zoneData:
    			zone=self.zoneData[i]
			if(len(zone.alert)>0):
				zonealerts+=" Zone"+str(zone.id)+" "+zone.alert
		self.ui.zoneAlertsText=zonealerts
		return
	
	def readSensors(self):
		# get data from serial RF sensors
		# get data from remote PI
		# all data in memory only in this function
		# get temperature
		# messages are 12chars aIDTYPEVALUE aIDAWAKE---- or aIDSLEEPING-
		# returns -100 on error, or the temperature as a float
		
		fim = time()+ self.TIMEOUT
		
		voltage = 0
		tempvalue = -100
		deviceid = ''
		while (time()<fim) and (tempvalue == -100):
			n = self.ser.inWaiting()
			if n != 0:
				data = self.ser.read(n)
				nb_msg = len(data) / 12
				for i in range (0, nb_msg):
					msg = data[i*12:(i+1)*12]
		
					deviceid = msg[1:3]
					if self.deviceData.has_key(deviceid):
						device=self.deviceData[deviceid]
						device.lastupdate=strftime(DATE_FORMAT,localtime())
			
						if msg[3:7] == "TEMP":
							tempvalue = msg[7:]
							device.temp=tempvalue
							self.dataFeed.append((strftime(DATE_FORMAT,localtime()), deviceid, "TEMP", tempvalue))

						if msg[3:7] == "BATT":
							voltage = msg[7:11]
							if voltage == "LOW":
								voltage = 0.1
							device.batt=voltage
							self.dataFeed.append((strftime(DATE_FORMAT,localtime()), deviceid+'B', "BATT", voltage))

			else:
				sleep(5)
		return

	def getPiSensorData(self):
		if(time()-self.lastGPUTempRead > 60):
			temp = ""
			temp = subprocess.check_output(["/opt/vc/bin/vcgencmd","measure_temp"],universal_newlines=True)
			temp = temp[5 : -3]
			device=self.deviceData['PI']
			device.lastupdate=strftime(DATE_FORMAT,localtime())
			device.temp=temp
			self.dataFeed.append((strftime(DATE_FORMAT,localtime()), "PI", "TEMP", temp))
			self.lastGPUTempRead = time()
		return

	def getConnectedSensorData(self):
		if(time()-self.lastTempPressHumidRead > 60):
			# get BME280 data
			temp=self.sensor.read_temperature()-1.0
			press=self.sensor.read_pressure()
			humid=self.sensor.read_humidity()
			self.pressure=press
			device=self.deviceData['BM']
			device.lastupdate=strftime(DATE_FORMAT,localtime())
			device.temp=temp
			device.press=press
			device.humid=humid
			self.dataFeed.append((strftime(DATE_FORMAT,localtime()), "BM", "TEMP", temp))
			self.dataFeed.append((strftime(DATE_FORMAT,localtime()), "BP", "PRESS", press))
			self.dataFeed.append((strftime(DATE_FORMAT,localtime()), "BH", "HUMID", humid))
			self.lastTempPressHumidRead = time()

	def getWeather(self):
		if(time()-self.lastWeatherRead > 1800):
			# get and parse AccuWeather data
			cur = re.compile('Currently: (.*)<')
			link = "http://rss.accuweather.com/rss/liveweather_rss.asp?metric=0&locCode=US|44022"
			f = urllib.urlopen(link)
			myfile = f.read()
			tempvalue = cur.search(myfile).group(1)
			temp=tempvalue[-4:-1]
			pos=tempvalue.find(":")
			description=tempvalue[0:-5] if pos<0 else tempvalue[0:pos]
			description=description.replace(" ","_").lower()
			# print("description = [" + description +"]")
			device=self.deviceData['AW']
			device.lastupdate=strftime(DATE_FORMAT,localtime())
			device.temp=(float(temp)-32)*5/9
			if device.desc<>description :
				self.ui.picSource='weather/'+description+'.jpg' if 6 < localtime()[3] < 18 else 'weather/'+description+'_dark.jpg'
			device.desc=description
			self.ui.weatherText = tempvalue
			self.dataFeed.append((strftime(DATE_FORMAT,localtime()), "AW", "NEWS", tempvalue))
						
			self.lastWeatherRead = time()
		return
	def setAlerts(self):
		# Reasons for alerts:
		# sensor battery level below 2.3
		# sensor not reporting ( sensor data age > 5x reporting )
		# temperature not under control = falling when attempting to raise
		#    alert if temp not correct direction for 10 minutes
		#    need control switch date time 
		if(time()-self.lastSetAlerts > 1800):
			for i in self.deviceData:
    				device=self.deviceData[i]
				device.alert=""
				if (not device.batt is None) & (device.batt<2.5):
    					device.alert="LOW"
					self.dataFeed.append((strftime(DATE_FORMAT,localtime()), "ALERT", "LOW Battery in "+device.location, device.batt))
					self.lastSetAlerts = time()
				if (len(device.lastupdate)>0) & (device.id!='AW'): 
					age = datetime.datetime.strptime(strftime(DATE_FORMAT,localtime()),DATE_FORMAT) - datetime.datetime.strptime(device.lastupdate,DATE_FORMAT)
					#print "{} {}".format(device.location,age.seconds)
					if ( age.seconds > 600 ):
						device.alert="OLD"
						self.dataFeed.append((strftime(DATE_FORMAT,localtime()), "ALERT", "NO Response in "+device.location, age.seconds))
						self.lastSetAlerts = time()
			for i in self.zoneData:
    				zone=self.zoneData[i]
				zone.alert=""
				if (zone.status):
					age = datetime.datetime.strptime(strftime(DATE_FORMAT,localtime()),DATE_FORMAT) - datetime.datetime.strptime(zone.lastupdate,DATE_FORMAT)
					if (age.seconds>600):
						zone.alert="OOC"
						self.dataFeed.append((strftime(DATE_FORMAT,localtime()), "ALERT", "OOC in zone "+str(zone.id), tformat(zone.average)))
						self.lastSetAlerts = time()
		return

	def uploadData(self):
		# put the data in the cloud or cache in a file until sucess
		# add it to the memory deque
		# if the deque > 10 try to upload it and any pending updates
		# else throw a flag for pending updates and write to a file
		if len(self.dataFeed)>10:
    			try:
				# write to a file
				#print "  write to file"
				with open("Output.txt", "a") as text_file:
					for record in self.dataFeed:
						text_file.write("{},{},{},{}\r\n".format(record[0],record[1],record[2],record[3]))
				# write to cloud
				#print "  write to cloud"

				self.myAWSIoTMQTTClient.publish("thermo", json.dumps(list(self.dataFeed)), 1)
				# clear the deque
				self.dataFeed.clear()
			except:
				print("Unexpected error in uploadData:", sys.exc_info()[0])
		return
		
	def downloadRequests(self):
		# get cloud data or web requests
		return
		
	def controlZone(self,zone,on,avg):
		zoneentry=self.zoneData[str(zone)]
		subprocess.call(["gpio", "-g", "write", str(zoneentry.port), "1" if on else "0"])
    		furnaceWasOn=False
		for i in self.zoneData:
			furnaceWasOn|=self.zoneData[i].status
		if(zoneentry.status != on):
			zoneentry.status=on
			furnaceIsOn=False
			for i in self.zoneData:
				furnaceIsOn|=self.zoneData[i].status
			if(furnaceIsOn!=furnaceWasOn):
				self.furnace.status=furnaceIsOn
				if (len(self.furnace.lastupdate)>0):
					age = datetime.datetime.strptime(strftime(DATE_FORMAT,localtime()),DATE_FORMAT) - datetime.datetime.strptime(self.furnace.lastupdate,DATE_FORMAT)
					# if it is now on  - age is how long it was off
					if(furnaceIsOn):
						self.furnace.offSeconds+=age.seconds
						if(age.seconds>self.furnace.maxRestSeconds):
							self.furnace.maxRestSeconds=age.seconds
					# if it is now off - age is how long it was on
					else:
						self.furnace.onSeconds+=age.seconds
						if(age.seconds>self.furnace.maxBurnSeconds):
							self.furnace.maxBurnSeconds=age.seconds
				self.furnace.lastupdate=strftime(DATE_FORMAT,localtime())
			zoneentry.lastupdate=strftime(DATE_FORMAT,localtime())
			zoneentry.triggertemp=avg
		return

	def takeAction(self):
		# contains all rules to make decisions based on data 
		for i in self.zoneData:
			zone=self.zoneData[i]
			zone.average=self.avgZone(zone.id)
			if(zone.average<10.0):
				self.controlZone(zone.id,False,zone.average)
				return
			#print "average in zone {} is {}".format(zone.id,zone.average)
    			if(zone.average<zone.setPoint-0.5):
    				self.controlZone(zone.id,True,zone.average)
    				#turn it on
			if(zone.average>zone.setPoint):
				self.controlZone(zone.id,False,zone.average)
    				#turn it off
		return
	
	def mainLoop(self,args):
		try:
			#print 'config'
			self.loadConfig()
			#print 'getWeather'
			self.getWeather()
			#print 'getPI'
			self.getPiSensorData()
			#print 'getBME'
			self.getConnectedSensorData()
			#print 'read'
			self.readSensors()
			#print 'alerts'
			self.setAlerts()
			#print 'update'
			self.updateDisplay()
			#print 'update shadow'
			self.updateDeviceShadow()
			#print 'upload'
			self.uploadData()
			#print 'download'
			self.downloadRequests()
			#print 'action'
			self.takeAction()
		except:
			type_, value_, traceback_ = sys.exc_info()
			print "EXCEPTION {}\r\n{}\r\n{}".format(type_, value_, traceback.format_tb(traceback_))
			self.dataFeed.append(value_)
		return
#discoverGGC(host, iotCAPath, certificatePath, privateKeyPath, clientId)

# read GGC Host Address from file
ggcAddrPath = GROUP_PATH + GGC_ADDR_NAME
rootCAPath = GROUP_PATH + CA_NAME
ggcAddr = getGGCAddr(ggcAddrPath)
print("GGC Host Address: " + ggcAddr)
print("GGC Group CA Path: " + rootCAPath)
print("Private Key of trafficLight thing Path: " + privateKeyPath)
print("Certificate of trafficLight thing Path: " + certificatePath)
print("Client ID(thing name for trafficLight): " + clientId)
print("Target shadow thing ID(thing name for trafficLight): " + thingName)

# Init AWSIoTMQTTShadowClient
myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(clientId)
myAWSIoTMQTTShadowClient.configureEndpoint(ggcAddr, 8883)
myAWSIoTMQTTShadowClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath)

# AWSIoTMQTTShadowClient configuration
myAWSIoTMQTTShadowClient.configureAutoReconnectBackoffTime(1, 32, 20)
myAWSIoTMQTTShadowClient.configureConnectDisconnectTimeout(10)  # 10 sec
myAWSIoTMQTTShadowClient.configureMQTTOperationTimeout(5)  # 5 sec

# Connect to AWS IoT
myAWSIoTMQTTShadowClient.connect()

# Create a deviceShadow with persistent subscription
deviceShadowHandler = myAWSIoTMQTTShadowClient.createShadowHandlerWithName(thingName, True)

# Listen on deltas - customShadowCallback_Delta will be called when a shadow delta message is received
deviceShadowHandler.shadowRegisterDeltaCallback(customShadowCallback_Delta)
Private_Key = "/home/pi/AWS/f58824458b-private.pem.key"
Client_ID = "IoT_System_Client2"
topic = 'IoT_System_Email_Alarm'

'''
topic = 'IoT_System_Email_Alarm'
Thing_Name = "anklet_pi"

Host_Name = "azjctapxbp7sc-ats.iot.ap-northeast-2.amazonaws.com"
Root_CA = "/home/pi/workspace/MQTT/anklet_pi/RootCA.crt"
Cert_File = "/home/pi/workspace/MQTT/anklet_pi/bc1b2abd97-certificate.pem.crt"
Private_Key = "/home/pi/workspace/MQTT/anklet_pi/bc1b2abd97-private.pem.key"
Client_ID = "anklet"

Client = AWSIoTMQTTShadowClient(Client_ID)
Client.configureEndpoint(Host_Name, port)
Client.configureCredentials(Root_CA, Private_Key, Cert_File)
Client.configureConnectDisconnectTimeout(10)
Client.configureMQTTOperationTimeout(5)
Client.connect()

Device = Client.createShadowHandlerWithName(Thing_Name, True)


def Callback_func(payload, responseStatus, token):
    print()
    print('UPDATE: $aws/things/' + Thing_Name + '/shadow/update/#')
    print("payload = " + payload)
    print("responseStatus = " + responseStatus)
    print("token = " + token)
def callback(payload, status, token):
    if status == "timeout":
        print(f'Timeout: {token}')
    if status == "accepted":
        payloadDict = json.loads(payload)
        print(f'Accepted: {token}')
        print(payload)
    if status == "rejected":
        print("Rejected: " + token)


with open('device_info.json') as f:
    dev = json.load(f)

shadowClient = AWSIoTMQTTShadowClient(dev['thingName'])
shadowClient.configureEndpoint(dev['endpoint'], 8883)
shadowClient.configureCredentials(f'{dev["certPath"]}/{dev["rootCert"]}',
                                  f'{dev["certPath"]}/{dev["privateKey"]}',
                                  f'{dev["certPath"]}/{dev["cert"]}')
shadowClient.configureAutoReconnectBackoffTime(1, 32, 20)
shadowClient.configureConnectDisconnectTimeout(10)
shadowClient.configureMQTTOperationTimeout(5)

print(f'Start updating the battery status : {dev["thingName"]}')

shadowClient.connect()
shadowHandler = shadowClient.createShadowHandlerWithName(
    dev['thingName'], True)
shadowHandler.shadowDelete(callback, 5)

prop = {'state': {'reported': {'batt': 100.0}}}
Пример #7
0
import json
import time
import os 
import random

#MQTT Shadow Istemci olusturma ve guvenlik sertifikalarini tanimlama
#Sertifa isimleri ile AWS IoT Thing indirdiginiz sertifika isimlerinin ayni olmasina dikkat edin.

currentPath=os.getcwd()
roboName=os.path.basename(currentPath)
print("RoboName--> "+roboName)

shadowClient=AWSIoTMQTTShadowClient(roboName)

#Ayarlar sayfasindaki IoTEndpoint buraya ekleyin
shadowClient.configureEndpoint("ENDPOINT BURAYA KOPYALANACAK",8883)
shadowClient.configureCredentials("../root-CA.crt","PrivateKey.pem","certificate.pem.crt")

shadowClientHandler=shadowClient.createShadowHandlerWithName("Robo1",True) # Robo1 Thing adi olarak statik tanimli, parametre de olabilir.
#JSON formatina encode eden fonksiyon
def toJSON(string):
        return json.dumps(string)

shadowClient.toJSON=toJSON

#Function to encode a payload into JSON
def json_encode(string):
        return json.dumps(string)

shadowClient.json_encode=json_encode
shadowClientHandler.json_encode=json_encode
Пример #8
0
def updateDeviceState(device_seq, device_state):
    host = "a3mfkf3z93nqt8.iot.us-west-2.amazonaws.com"
    rootCAPath = "certs/root-CA.crt"
    certificatePath = "certs/team55device%s.cert.pem" % (device_seq+1)
    privateKeyPath = "certs/team55device%s.private.key" % (device_seq+1)
    clientId = "team55"

    thingName = "team55device%s" % (device_seq+1)

    # Custom Shadow callback
    def customShadowCallback_Update(payload, responseStatus, token):
        # payload is a JSON string ready to be parsed using json.loads(...)
        # in both Py2.x and Py3.x
        if responseStatus == "timeout":
            print("Update request " + token + " time out!")
        if responseStatus == "accepted":
            payloadDict = json.loads(payload)
            print("~~~~~~~~~~~~~~~~~~~~~~~")
            print("Update request with token: " + token + " accepted!")
            print("property: " + json.dumps(payloadDict["state"]["desired"]))
            print("~~~~~~~~~~~~~~~~~~~~~~~\n\n")
        if responseStatus == "rejected":
            print("Update request " + token + " rejected!")

    def customShadowCallback_Delete(payload, responseStatus, token):
        if responseStatus == "timeout":
            print("Delete request " + token + " time out!")
        if responseStatus == "accepted":
            print("~~~~~~~~~~~~~~~~~~~~~~~")
            print("Delete request with token: " + token + " accepted!")
            print("~~~~~~~~~~~~~~~~~~~~~~~\n\n")
        if responseStatus == "rejected":
            print("Delete request " + token + " rejected!")

    # logging
    logger = logging.getLogger("AWSIoTPythonSDK.core")
    logger.setLevel(logging.DEBUG)
    streamHandler = logging.StreamHandler()
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    streamHandler.setFormatter(formatter)
    logger.addHandler(streamHandler)

    # Init AWSIoTMQTTShadowClient
    myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(clientId)
    myAWSIoTMQTTShadowClient.configureEndpoint(host, 8883)
    myAWSIoTMQTTShadowClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath)

    # AWSIoTMQTTShadowClient configuration
    myAWSIoTMQTTShadowClient.configureAutoReconnectBackoffTime(1, 32, 20)
    myAWSIoTMQTTShadowClient.configureConnectDisconnectTimeout(10)  # 10 sec
    myAWSIoTMQTTShadowClient.configureMQTTOperationTimeout(5)  # 5 sec

    myAWSIoTMQTTShadowClient.connect()

    # Create a deviceShadow with persistent subscription
    deviceShadowHandler = myAWSIoTMQTTShadowClient.createShadowHandlerWithName(thingName, True)

    # Delete shadow JSON doc
    deviceShadowHandler.shadowDelete(customShadowCallback_Delete, 5)

    deviceShadowHandler.shadowUpdate(json.dumps({"state": {"desired": device_state}}), customShadowCallback_Update, 5)

    time.sleep(5)

    myAWSIoTMQTTShadowClient.disconnect()
if not args.useWebsocket and not args.port:  # When no port override for non-WebSocket, default to 8883
    port = 8883
 
# Configure logging
logger = logging.getLogger("AWSIoTPythonSDK.core")
logger.setLevel(logging.DEBUG)
streamHandler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
streamHandler.setFormatter(formatter)
logger.addHandler(streamHandler)

# Init AWSIoTMQTTShadowClient
myAWSIoTMQTTShadowClient = None
if useWebsocket:
    myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(clientId, useWebsocket=True)
    myAWSIoTMQTTShadowClient.configureEndpoint(host, port)
    myAWSIoTMQTTShadowClient.configureCredentials(rootCAPath)
else:
    myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(clientId)
    myAWSIoTMQTTShadowClient.configureEndpoint(host, port)
    myAWSIoTMQTTShadowClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath)
 
# AWSIoTMQTTShadowClient configuration
myAWSIoTMQTTShadowClient.configureAutoReconnectBackoffTime(1, 32, 20)
myAWSIoTMQTTShadowClient.configureConnectDisconnectTimeout(10)  # 10 sec
myAWSIoTMQTTShadowClient.configureMQTTOperationTimeout(5)  # 5 sec
 
# Connect to AWS IoT
myAWSIoTMQTTShadowClient.connect()
 
# Create a deviceShadow with persistent subscription
Пример #10
0
#!/usr/bin/python3
# light_controller.py
# -- This is a demo program for AWS IoT Shadow
# -- It simulates a light controller that's connected to AWS IoT Core and use Shadow to control a light
# Author: Randy Lin

import json
import time
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTShadowClient
import configparser
import random
import time

#Setup Shadow client and security certificates
shadowc = AWSIoTMQTTShadowClient('Light1_controller')
shadowc.configureEndpoint(
    "ChangeToYourEndpoint.ats.iot.cn-north-1.amazonaws.com.cn", 8883)

shadowc.configureCredentials('./root-CA.crt', './MyIoTDevice.private.key',
                             './MyIoTDevice.cert.pem')

#Connect to IoT Core
shadowc.connect()
print('Shadow Client Connected to IoT Core')

#Create Device Shadow Handler with persistent subscription
deviceShadowHandler = shadowc.createShadowHandlerWithName('MyIoTDevice', True)


#Callback: Shadow Update
def shadow_update_callback(payload, responseStatus, token):
    if responseStatus == 'timeout':
Пример #11
0
        print("Error in discovery!")
        print("Type: %s" % str(type(e)))
        print("Error message: %s" % e.message)
        retryCount -= 1
        print("\n%d/%d retries left\n" % (retryCount, MAX_DISCOVERY_RETRIES))
        print("Backing off...\n")
        backOffCore.backOff()

if not discovered:
    print("Discovery failed after %d retries. Exiting...\n" %
          (MAX_DISCOVERY_RETRIES))
    sys.exit(-1)

# Init AWSIoTMQTTShadowClient
myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(clientId)
myAWSIoTMQTTShadowClient.configureEndpoint(host, port)
myAWSIoTMQTTShadowClient.configureCredentials(groupCA, privateKeyPath,
                                              certificatePath)
# myAWSIoTMQTTShadowClient.getMQTTConnection().onMessage = customOnMessage

# AWSIoTMQTTShadowClient configuration
myAWSIoTMQTTShadowClient.configureAutoReconnectBackoffTime(1, 32, 20)
myAWSIoTMQTTShadowClient.configureConnectDisconnectTimeout(10)  # 10 sec
myAWSIoTMQTTShadowClient.configureMQTTOperationTimeout(5)  # 5 sec
myAWSIoTMQTTShadowClient.getMQTTConnection().configureOfflinePublishQueueing(
    10)  # Infinite offline Publish queueing
myAWSIoTMQTTShadowClient.getMQTTConnection().configureDrainingFrequency(
    2)  # Draining: 2 Hz

# Create a deviceShadow with persistent subscription
deviceShadowHandler = myAWSIoTMQTTShadowClient.createShadowHandlerWithName(
Пример #12
0
class SodPlug(object):
    def __init__(self, **kwargs):
        self.device_name = kwargs.get('DeviceName')
        print('Device name: {}'.format(self.device_name))
        self.device_root = kwargs.get('DeviceRoot', './devices')
        self.device_path = kwargs.get(
            'DevicePath',
            os.path.join(self.device_root, 'credentials', self.device_name))
        self.iot_ca_path = kwargs.get('IotCaPath', './root/root-cert.pem')
        self.cert_path = kwargs.get('CertPath',
                                    os.path.join(self.device_path, 'cert.pem'))
        self.private_key_path = kwargs.get(
            'PrivateKeyPath', os.path.join(self.device_path, 'private.key'))
        self.iot_endpoint = kwargs.get('IotEndPoint')
        self.ca_name = kwargs.get('CaName', 'root-ca.cert')
        self.shadow_thing_name = kwargs.get('ThingName', self.device_name)
        self.max_discovery_retries = int(
            kwargs.get('MaxDiscoveryRetries', '10'))  # noqa: E501
        self.ggc_addr_name = kwargs.get('CoreName', 'ggc-core')
        self.root_ca_path = os.path.join(self.device_path, self.ca_name)
        print('iot_endpoint: {}'.format(self.iot_endpoint))
        print('shadow_thing_name: {}'.format(self.shadow_thing_name))
        for key, value in kwargs.items():
            setattr(self, key, value)
        self.gg = boto3.client('greengrass')
        self.iot_client = boto3.client('iot')
        self.iot_data = boto3.client('iot-data')
        self.publish_only = kwargs.get('PublishOnly', False)
        self.custom_shadow_callback = kwargs.get(
            'CustomShadowCallback', self.customShadowCallback_Update)
        self.delta_callback = kwargs.get('DeltaCallback', self.delta_callback)
        print(self.custom_shadow_callback)
        self.get_thing()

    def get_thing(self):
        response = self.iot_client.describe_thing(
            thingName=self.shadow_thing_name)
        self.thing_arn = response['thingArn']

    def get_shadow(self, thing_name=None):
        if not thing_name:
            thing_name = self.shadow_thing_name
        response = self.iot_data.get_thing_shadow(thingName=thing_name)
        shadowData = json.loads(response["payload"].read().decode("utf-8"))
        return (shadowData)

    def update_shadow(self, **kwargs):
        desired = kwargs.get('Desired')
        reported = kwargs.get('Reported')
        doc = {}
        doc['state'] = {}
        if desired:
            doc['state']['desired'] = desired
        if reported:
            doc['state']['reported'] = reported
        json_payload = json.dumps(doc)
        print('Updating shadow: {}'.format(json_payload))
        print(self.custom_shadow_callback)
        self.device_shadow_handler.shadowUpdate(
            json_payload,
            self.custom_shadow_callback,  # noqa E:501
            10)

    def does_root_cert_exist(self):
        return os.path.isfile(self.root_ca_path)

    def check_root_cert(self):
        if not self.does_root_cert_exist():
            self.discover_ggc()
        else:
            self.get_ggc_addr()
            print('Greengrass core has already been discovered.')

    def configure_mqtt_client(self):
        self.mqtt_client = self.mqtt_shadow_client.getMQTTConnection()
        self.mqtt_client.configureAutoReconnectBackoffTime(1, 32, 20)
        self.mqtt_client.configureOfflinePublishQueueing(-1)
        self.mqtt_client.configureDrainingFrequency(2)  # Draining: 2 Hz
        self.mqtt_client.configureConnectDisconnectTimeout(10)  # 10 sec
        self.mqtt_client.configureMQTTOperationTimeout(5)  # 5 sec

    def configure_shadow_client(self):
        self.mqtt_shadow_client = AWSIoTMQTTShadowClient(self.device_name)
        print('Created shadow client for {}'.format(self.device_name))
        self.mqtt_shadow_client.configureEndpoint(self.ggc_host_addr,
                                                  8883)  # noqa: E501
        self.mqtt_shadow_client.configureCredentials(self.root_ca_path,
                                                     self.private_key_path,
                                                     self.cert_path)

        # AWSIoTMQTTShadowClient configuration
        self.mqtt_shadow_client.configureAutoReconnectBackoffTime(
            1, 32, 20)  # noqa: E501
        self.mqtt_shadow_client.configureConnectDisconnectTimeout(10)
        self.mqtt_shadow_client.configureMQTTOperationTimeout(5)
        self.mqtt_shadow_client.connect()

    def delta_callback(self, payload, responseStatus, token):
        print('delta received')
        pass

    def register_handlers(self):
        self.device_shadow_handler = self.mqtt_shadow_client.createShadowHandlerWithName(
            self.shadow_thing_name, True)  # noqa: E501
        print('Registered shadow handlers for {}'.format(
            self.shadow_thing_name))  # noqa: E501
        if self.publish_only:
            return
        self.device_shadow_handler.shadowRegisterDeltaCallback(
            self.delta_callback)  # noqa: E501
        print('Registered delta callback for {}'.format(
            self.shadow_thing_name))  # noqa: E501

    def on_registered(self):
        print('Device {} is online'.format(self.device_name))

    def register(self, **kwargs):
        self.check_root_cert()
        self.configure_shadow_client()
        self.configure_mqtt_client()
        self.register_handlers()
        self.on_registered()

    def isIpAddress(self, value):
        match = re.match(r'^\d{1,3}\.\d{1,3}\.\d{1,3}', value)
        if match:
            return True
        return False

    def get_ggc_addr(self):
        ggcHostPath = os.path.join(self.device_path, self.ggc_addr_name)
        f = open(ggcHostPath, 'r')
        self.ggc_host_addr = f.readline()
        print('Greengrass core: {}'.format(self.ggc_host_addr))

    def discover_ggc(self):
        backOffCore = ProgressiveBackOffCore()
        discoveryInfoProvider = DiscoveryInfoProvider()
        discoveryInfoProvider.configureEndpoint(self.iot_endpoint)
        discoveryInfoProvider.configureCredentials(self.iot_ca_path,
                                                   self.cert_path,
                                                   self.private_key_path)
        print('Endpoint: {}'.format(self.iot_endpoint))
        print('iot_ca_path: {}'.format(self.iot_ca_path))
        print('cert_path: {}'.format(self.cert_path))
        print('private_key_path: {}'.format(self.private_key_path))
        print('device_name: {}'.format(self.device_name))
        discoveryInfoProvider.configureTimeout(10)  # 10 sec
        retryCount = self.max_discovery_retries
        discovered = False
        groupCA = None
        coreInfo = None
        while retryCount != 0:
            try:
                discoveryInfo = discoveryInfoProvider.discover(
                    self.device_name)  # noqa: E501
                caList = discoveryInfo.getAllCas()
                coreList = discoveryInfo.getAllCores()
                groupId, ca = caList[0]
                coreInfo = coreList[0]
                print('Discovered GGC: ' + coreInfo.coreThingArn +
                      ' from Group: ' + groupId)
                host_addr = ''

                for addr in coreInfo.connectivityInfoList:
                    host_addr = addr.host
                    if self.isIpAddress(host_addr):
                        break

                print('Discovered GGC Host Address: ' + host_addr)
                self.ggc_host_addr = host_addr
                print('Now we persist the connectivity/identity information')
                groupCA = os.path.join(self.device_path, self.ca_name)
                ggcHostPath = os.path.join(self.device_path,
                                           self.ggc_addr_name)  # noqa: E501
                groupCAFile = open(groupCA, 'w')
                groupCAFile.write(ca)
                groupCAFile.close()
                groupHostFile = open(ggcHostPath, 'w')
                groupHostFile.write(host_addr)
                groupHostFile.close()

                discovered = True
                print('Now proceed to the connecting flow...')
                break
            except DiscoveryInvalidRequestException as e:
                print('Invalid discovery request detected!')
                print('Type: ' + str(type(e)))
                print('Error message: ' + e.message)
                print('Stopping...')
                break
            except BaseException as e:
                print('Error in discovery!')
                print('Type: ' + str(type(e)))
                print('Error message: ' + e.message)
                retryCount -= 1
                raise
                print('\n' + str(retryCount) + '/' +
                      str(self.max_discovery_retries) + ' retries left\n')
                print('Backing off...\n')
                backOffCore.backOff()

        if not discovered:
            print('Discovery failed after ' + str(self.max_discovery_retries) +
                  ' retries. Exiting...\n')
            sys.exit(-1)

    # Custom Shadow callback for updating the reported state in shadow
    def customShadowCallback_Update(self, payload, responseStatus, token):
        print(payload)
        if responseStatus == 'timeout':
            print('Update request ' + token + ' time out!')
        if responseStatus == 'accepted':
            print('~~~~~~~~~~ Shadow Update Accepted ~~~~~~~~~~~~~')
            print('Update request with token: ' + token + ' accepted!')
            print(payload)
            print('~~~~~~~~~~~~~~~~~~~~~~~\n\n')
        if responseStatus == 'rejected':
            print('Update request ' + token + ' rejected!')

    def publish(self, topic, message, qos_level=0):
        print('Publishing {} to {}'.format(message, topic))
        if (self.mqtt_client.publish(topic, json.dumps(message), qos_level)):
            print('PUBLISHED')
        else:
            print('NOT PUBLISHED')

    def update_device_shadow(self, device, message, qos_level=0):
        desired = {'state': {'desired': message}}
        topic = '$aws/things/{}/shadow/update'.format(device)
        print('Publishing {} to {}'.format(desired, topic))
        if (self.mqtt_client.publish(topic, json.dumps(desired), qos_level)):
            print('PUBLISHED')
        else:
            print('NOT PUBLISHED')
Пример #13
0
        payloadDict = json.loads(payload)
        print("~~~~~~~~~~~~~~~~~~~~~~~")
        print("Update request with token: " + token + " accepted!")
        print("property: " + str(payloadDict["state"]["desired"]["property"]))
        print("~~~~~~~~~~~~~~~~~~~~~~~\n\n")
    if responseStatus == "rejected":
        print("Update request " + token + " rejected!")


# For certificate based connection
myShadowClient = AWSIoTMQTTShadowClient("pi")
# For Websocket connection
# myMQTTClient = AWSIoTMQTTClient("myClientID", useWebsocket=True)
# Configurations
# For TLS mutual authentication
myShadowClient.configureEndpoint(
    "a16h9u0dkdtqab.iot.ap-southeast-1.amazonaws.com", 8883)
# For Websocket
# myShadowClient.configureEndpoint("YOUR.ENDPOINT", 443)
myShadowClient.configureCredentials(
    "/home/pi/awsCertificate/root-CA.crt",
    "/home/pi/awsCertificate/1f452c99e4-private.pem.key",
    "/home/pi/awsCertificate/1f452c99e4-certificate.pem.crt")
# For Websocket, we only need to configure the root CA
# myShadowClient.configureCredentials("YOUR/ROOT/CA/PATH")
myShadowClient.configureConnectDisconnectTimeout(10)  # 10 sec
myShadowClient.configureMQTTOperationTimeout(5)  # 5 sec

myShadowClient.connect()
# Create a device shadow instance using persistent subscription

# Retrieve the AWS IoT MQTT Client used in the AWS IoT MQTT Shadow Client,naming the shadow as "raspberrypi"
Пример #14
0
import json
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTShadowClient

# For certificate based connection
myShadowClient = AWSIoTMQTTShadowClient("myClientID")
#myShadowClient.configureEndpoint("-", 8$
#myShadowClient.configureCredentials("/home/pi/aws/AmazonRootCA1.pem","/home/pi/aws/c$
myShadowClient.configureEndpoint("endpoint", 8883)
myShadowClient.configureCredentials("/home/pi/aws/AmazonRootCA1.pem","/h.key","/home/pi/aws/ccate.$

#myShadowClient.configureConnectDisconnectTimeout(10)  # 10 sec
#myShadowClient.configureMQTTOperationTimeout(5)  # 5 sec
#myMQTTClient.connect()
myMQTTClient = myShadowClient.getMQTTConnection()
myMQTTClient.connect()
data  = {
    "state" : {
        "desired" : {
            "color" : "red",
            "power" : "on"
         }
     }
}
myMQTTClient.publish("$aws/things/test/shadow/update", json.dumps(data), 1)
myMQTTClient.disconnect()



Пример #15
0
if not args.useWebsocket and not args.port:  # When no port override for non-WebSocket, default to 8883
    port = 8883

# Configure logging
logger = logging.getLogger("AWSIoTPythonSDK.core")
logger.setLevel(logging.DEBUG)
streamHandler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
streamHandler.setFormatter(formatter)
logger.addHandler(streamHandler)

# Init AWSIoTMQTTShadowClient
myAWSIoTMQTTShadowClient = None
if useWebsocket:
    myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(clientId, useWebsocket=True)
    myAWSIoTMQTTShadowClient.configureEndpoint(host, port)
    myAWSIoTMQTTShadowClient.configureCredentials(rootCAPath)
else:
    myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(clientId)
    myAWSIoTMQTTShadowClient.configureEndpoint(host, port)
    myAWSIoTMQTTShadowClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath)

# AWSIoTMQTTShadowClient configuration
myAWSIoTMQTTShadowClient.configureAutoReconnectBackoffTime(1, 32, 20)
myAWSIoTMQTTShadowClient.configureConnectDisconnectTimeout(10)  # 10 sec
myAWSIoTMQTTShadowClient.configureMQTTOperationTimeout(5)  # 5 sec

# Connect to AWS IoT
myAWSIoTMQTTShadowClient.connect()

# Create a deviceShadow with persistent subscription
Пример #16
0
class ShadowClient(object):

    client = None
    bot = None

    def __init__(self, client_id, end_point, root_ca, private_key, certificate):
        """

        :param client_id:
        :param end_point:
        :param root_ca:
        :param private_key:
        :param certificate:
        """
        self.client = AWSIoTMQTTShadowClient(client_id)
        self.client.configureEndpoint(end_point, 8883)
        self.client.configureCredentials(root_ca, private_key, certificate)
        self.client.configureAutoReconnectBackoffTime(2, 32, 20)
        self.client.configureConnectDisconnectTimeout(10)  # 10 sec
        self.client.configureMQTTOperationTimeout(5)  # 5 sec

    def connect(self):
        """
        接続処理
        :return: 結果(True:成功、False:失敗)
        """
        return self.client.connect()

    def create_shadow_handler_with_name(self, shadow_name):
        """
        デバイスShadowハンドラ作成
        :return: デバイスShadowオブジェクト
        """
        self.bot = self.client.createShadowHandlerWithName(shadow_name, True)

    def shadow_get(self, call_back):
        """
        Thing Shadowデータの最新データ取得
        :param call_back: レスポンスを取得するコールバック関数
        :return: なし
        """
        self.bot.shadowGet(call_back, 5)

    def shadow_update(self, payload, call_back):
        """
        Thing Shadowデータの更新
        :param payload: 送信データ
        :param call_back: レスポンスを取得するコールバック関数
        :return: なし
        """
        self.bot.shadowUpdate(payload, call_back, 5)

    def shadow_register_delta_callback(self, callback):
        """
        Thing Shadow deltaデータ発生時の処理登録
        :param callback: deltaデータ発生時のコールバック関数
        :return:
        """
        if self.bot:
            self.bot.shadowRegisterDeltaCallback(callback)

    def disconnect(self):
        """
        切断処理
        :return: 結果(True:成功、False:失敗)
        """
        return self.client.disconnect()
Пример #17
0
    data['Moisture'] = format(poller.parameter_value(MI_MOISTURE))
    data['Light'] = format(poller.parameter_value(MI_LIGHT))
    data['Conductivity'] = format(poller.parameter_value(MI_CONDUCTIVITY))
    data['Battery'] = format(poller.parameter_value(MI_BATTERY))
    data['DateTime'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    return data


# For certificate based connection
iot = AWSIoTMQTTClient('iot-data')
iot_shadow = AWSIoTMQTTShadowClient('iot-shadow')

# For TLS mutual authentication
iot.configureEndpoint("YOUR.ENDPOINT", 8883)
iot_shadow.configureEndpoint("YOUR.ENDPOINT", 8883)

iot.configureCredentials("YOUR/ROOT/CA/PATH", "YOUR/PRIAVTEKEY/PATH",
                         "YOUR/CERTIFICATE/PATH")
iot_shadow.configureCredentials("YOUR/ROOT/CA/PATH", "YOUR/PRIAVTEKEY/PATH",
                                "YOUR/CERTIFICATE/PATH")

iot.configureAutoReconnectBackoffTime(1, 32, 20)
iot.configureOfflinePublishQueueing(-1)  # Infinite offline Publish queueing
iot.configureDrainingFrequency(2)  # Draining: 2 Hz
iot.configureConnectDisconnectTimeout(10)  # 10 sec
iot.configureMQTTOperationTimeout(5)  # 5 sec

iot_shadow.configureAutoReconnectBackoffTime(1, 32, 20)
iot_shadow.configureConnectDisconnectTimeout(10)  # 10 sec
iot_shadow.configureMQTTOperationTimeout(5)  # 5 sec
Пример #18
0
class IoTClient:
    _redis = None

    def __init__(self):
        path = os.path.abspath(os.path.dirname(__file__))

        self._shadowC = AWSIoTMQTTShadowClient("shadow")
        self._shadowC.configureEndpoint(
            "a1g1flllk3y7ps.iot.ap-northeast-1.amazonaws.com", 8883)
        self._shadowC.configureCredentials(
            os.path.join(path, "credentials/aws/aws-root.pem"),
            os.path.join(path, "credentials/device/private.pem.key"),
            os.path.join(path, "./credentials/device/certificate.pem.crt"))
        self._shadowC.configureConnectDisconnectTimeout(10)
        self._shadowC.configureMQTTOperationTimeout(5)

        # For certificate based connection
        self._mqttC = AWSIoTMQTTClient("regular")
        self._mqttC.configureEndpoint(
            "a1g1flllk3y7ps.iot.ap-northeast-1.amazonaws.com", 8883)
        self._mqttC.configureCredentials(
            os.path.join(path, "credentials/aws/aws-root.pem"),
            os.path.join(path, "credentials/device/private.pem.key"),
            os.path.join(path, "./credentials/device/certificate.pem.crt"))

        self._mqttC.configureOfflinePublishQueueing(
            -1)  # Infinite offline Publish queueing
        self._mqttC.configureDrainingFrequency(2)  # Draining: 2 Hz
        self._mqttC.configureConnectDisconnectTimeout(10)  # 10 sec
        self._mqttC.configureMQTTOperationTimeout(5)  # 5 sec

    def __del__(self):
        try:
            self._shadowC.disconnect()
            self._mqttC.disconnect()
        except Exception:
            pass

    def connect(self):
        self._redis = redis.Redis(host='localhost', port=6379)

        try:
            self._redis.get(
                "test")  # getting None returns None or throws an exception
        except (redis.exceptions.ConnectionError,
                redis.exceptions.BusyLoadingError):
            print("Failed to connect to Redis server")
            return False

        connected = self._shadowC.connect() and self._mqttC.connect()

        if connected:
            self._shadowD = self._shadowC.createShadowHandlerWithName(
                "Air-RME-test", True)

            self._shadowD.shadowGet(self._setStateCallback, 5)

            self._shadowD.shadowRegisterDeltaCallback(self._echoCallback)
        return connected

    def _setStateCallback(self, payload, responseStatus, token):
        self._state = json.loads(payload)
        reported = '{"state":{"reported":' + json.dumps(
            self._state["state"]["desired"]) + '}}'
        self._redis.rpush("order", json.dumps(self._state["state"]["desired"]))
        print(self._redis.lpop("order").decode('utf-8'))
        self._shadowD.shadowUpdate(reported, None, 5)

    def _echoCallback(self, payload, responseStatus, token):
        print('--- Update Received ---')
        print("Status: " + responseStatus)
        p = json.loads(payload)
        self._state["state"]["desired"] = {
            **self._state["state"]["desired"],
            **p["state"]
        }
        print(json.dumps(json.loads(payload), indent=4, sort_keys=True))
        print('--- End of Update ---')
        reported = '{"state":{"reported":' + json.dumps(
            self._state["state"]["desired"]) + '}}'

        self._redis.rpush("order", json.dumps(self._state["state"]["desired"]))
        self._shadowD.shadowUpdate(reported, None, 5)

    def publish(self, topic, message):
        self._mqttC.publish(topic, json.dumps(message), 0)

    def run(self):
        print("Trying to connect to MQTT broker...")

        if self.connect():
            print("Connected")

            lastTemp = 0
            lastHum = 0

            while True:
                humidity, temperature = sensor_data.get_temperature_info()

                if lastTemp != temperature or lastHum != humidity:
                    data = {"temp": temperature, "hum": humidity}

                    self.publish("/Air-RME-test/sensor", data)
                    lastTemp = temperature
                    lastHum = humidity

                time.sleep(1)
        else:
            print("Connection failed.")

        return
Пример #19
0
# Author: Randy Lin

import json
import time
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTShadowClient
import configparser
import random
import time

#Load configuration from config.ini
config = configparser.ConfigParser()
config.read('config.ini')

#Setup Shadow client and security certificates
shadowc = AWSIoTMQTTShadowClient('Light1_controller')
shadowc.configureEndpoint(config['Endpoints']['BJS_IOT_ENDPOINT'],
                          int(config['Endpoints']['BJS_IOT_ENDPOINT_PORT']))
shadowc.configureCredentials(config['Certs']['ROOT_CA'],
                             config['Certs']['LIGHT_1_PRIVATE_KEY'],
                             config['Certs']['LIGHT_1_CERT'])

#Connect to IoT Core
shadowc.connect()
print('Shadow Client Connected to IoT Core')

#Create Device Shadow Handler with persistent subscription
deviceShadowHandler = shadowc.createShadowHandlerWithName('Light1', True)


#Callback: Shadow Update
def shadow_update_callback(payload, responseStatus, token):
    if responseStatus == 'timeout':
# Parse command line arguments
args = parseArgs()

if not args.certificatePath or not args.privateKeyPath:
    parser.error("Missing credentials for authentication.")
    exit(2)

# If no --port argument is passed, default to 8883
if not args.port:
    args.port = 8883

# Init AWSIoTMQTTShadowClient
myAWSIoTMQTTShadowClient = None
myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(args.clientId)
myAWSIoTMQTTShadowClient.configureEndpoint(args.host, args.port)
myAWSIoTMQTTShadowClient.configureCredentials(args.rootCAPath,
                                              args.privateKeyPath,
                                              args.certificatePath)

# AWSIoTMQTTShadowClient connection configuration
myAWSIoTMQTTShadowClient.configureAutoReconnectBackoffTime(1, 32, 20)
myAWSIoTMQTTShadowClient.configureConnectDisconnectTimeout(10)  # 10 sec
myAWSIoTMQTTShadowClient.configureMQTTOperationTimeout(5)  # 5 sec

# Intialize SenseHat
sh = SenseHat()

# Connect to AWS IoT
myAWSIoTMQTTShadowClient.connect()
class AWSIoTMQTTShadowClientGenerator:

    def __init__(self, host, rootCAPath, certificatePath, privateKeyPath, thingName, clientId, useWebsocket=False):
        self.host = host
        self.rootCAPath = rootCAPath
        self.certificatePath = certificatePath
        self.privateKeyPath = privateKeyPath
        self.useWebsocket = useWebsocket
        self.thingName = thingName
        self.clientId = clientId

        if useWebsocket and certificatePath and privateKeyPath:
            print("X.509 cert authentication and WebSocket are mutual exclusive. Please pick one.")
            exit(2)

        if not useWebsocket and (not certificatePath or not privateKeyPath):
            print("Missing credentials for authentication.")
            exit(2)

        # Configure logging
        logger = logging.getLogger("AWSIoTPythonSDK.core")
        logger.setLevel(logging.INFO)
        streamHandler = logging.StreamHandler()
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        streamHandler.setFormatter(formatter)
        logger.addHandler(streamHandler)

        # Init AWSIoTMQTTShadowClient
        self.myAWSIoTMQTTShadowClient = None
        if useWebsocket:
            self.myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(clientId, useWebsocket=True)
            self.myAWSIoTMQTTShadowClient.configureEndpoint(host, 443)
            self.myAWSIoTMQTTShadowClient.configureCredentials(rootCAPath)
        else:
            self.myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(clientId)
            self.myAWSIoTMQTTShadowClient.configureEndpoint(host, 8883)
            self.myAWSIoTMQTTShadowClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath)

        # AWSIoTMQTTShadowClient configuration
        self.myAWSIoTMQTTShadowClient.configureAutoReconnectBackoffTime(1, 32, 20)
        self.myAWSIoTMQTTShadowClient.configureConnectDisconnectTimeout(10)  # 10 sec
        self.myAWSIoTMQTTShadowClient.configureMQTTOperationTimeout(5)  # 5 sec

        # Connect to AWS IoT
        self.myAWSIoTMQTTShadowClient.connect()

        # Create a deviceShadow with persistent subscription
        self.deviceShadowHandler = self.myAWSIoTMQTTShadowClient.createShadowHandlerWithName(thingName, True)
        self.shadowCallbackContainer_Bot = ShadowCallbackContainer(self.deviceShadowHandler)

        # Listen on deltas
        self.deviceShadowHandler.shadowRegisterDeltaCallback(self.shadowCallbackContainer_Bot.customShadowCallbackDelta)

        # Create the initial State
        self._desired_state = {}
        self._reported_state = {}
        self._devices = []


    def getState(self):
        _r = '"reported": {"ble_devices":' + json.dumps(self._reported_state.values()) + '}'
        _d = '"desired": {"ble_devices":' + json.dumps(self._desired_state.values()) + '}'
        return '{"state": {' + _r + ', ' + _d + '} }'


    def updateState(self, value):
        self._reported_state[value["MAC"]] = value
        for x in self._devices:
            self._desired_state[x]["color"] = value["color"]
        print (str(datetime.now()) + " Desired state values: " + json.dumps(self._desired_state.values()))
        print (str(datetime.now()) + " Reported state values: " + json.dumps(self._reported_state.values()))
        return self.getState()


    def registerDeviceAddress(self, address):
        print "AWSIoTMQTTShadowClientGenerator is registering device: " + address
        self._devices.append(address)
        # Initialize dictionary for this BLE device. Set color to off
        self._desired_state[address] = { "MAC": address, "color": "21430000009b"}


    def registerNotificationDelegate(self, notificationDelgate):
        #self.notificationDelgate = notificationDelgate
        self.shadowCallbackContainer_Bot.setNotificationDelegate(notificationDelgate)
Пример #22
0
class Shadow():
    def __init__(self, canvas):
        self.canvas = canvas
        self._logger = canvas._logger
        self._hub_id = canvas.hub_yaml["canvas-hub"]["id"]
        self._myShadowClient = None
        self._myDeviceShadow = None
        self._connectThread = None

        self._initialize()

    ##############
    # PRIVATE
    ##############

    def _initialize(self):
        mosaic_path = os.path.expanduser('~') + "/.mosaicdata/"
        root_ca_path = mosaic_path + "root-ca.crt"
        private_key_path = mosaic_path + "private.pem.key"
        certificate_path = mosaic_path + "certificate.pem.crt"

        # Initialization
        self._myShadowClient = AWSIoTMQTTShadowClient(self._hub_id)
        self._myShadowClient.configureEndpoint(constants.SHADOW_CLIENT_HOST,
                                               8883)
        self._myShadowClient.configureCredentials(root_ca_path,
                                                  private_key_path,
                                                  certificate_path)

        # Configuration
        self._myShadowClient.configureAutoReconnectBackoffTime(1, 32, 20)
        self._myShadowClient.configureConnectDisconnectTimeout(15)  # 15 sec
        self._myShadowClient.configureMQTTOperationTimeout(5)  # 5 sec
        self._myShadowClient.onOnline = self._onOnline
        self._myShadowClient.onOffline = self._onOffline
        self._logger.info("Shadow client initialized")

    def _connectShadowClient(self):
        # Connect to AWS IoT
        try:
            self._logger.info("Connecting shadow client...")
            self._myShadowClient.connect(30)
            self._subscribeShadowDeviceToTopic()
        except:
            self._logger.info("Could not connect shadow client")

    def _subscribeShadowDeviceToTopic(self):
        # Create device shadow with persistent subscription to the topic (i.e current hub)
        try:
            self._logger.info(
                "Device shadow subscribing to current hub topic...")
            shadow_topic = "canvas-hub-" + self._hub_id
            self._myDeviceShadow = self._myShadowClient.createShadowHandlerWithName(
                shadow_topic, True)
            self._myDeviceShadow.shadowRegisterDeltaCallback(
                self._onDelta)  # initialize listener for device shadow deltas
            self._logger.info("Device shadow successfully subscribed to topic")
            self.getData()
        except:
            self._logger.info(
                "Could not subscribe device shadow to the current hub topic")

    def _startConnectThread(self):
        if self._connectThread is not None:
            self._stopConnectThread()

        self._connectThreadStop = False
        self._connectThread = threading.Thread(target=self._connectToAWS)
        self._connectThread.daemon = True
        self._connectThread.start()

    def _connectToAWS(self):
        while not self._connectThreadStop:
            self._connectShadowClient()
            time.sleep(30)

    def _stopConnectThread(self):
        self._connectThreadStop = True
        if self._connectThread and threading.current_thread(
        ) != self._connectThread:
            self._connectThread.join()
        self._connectThread = None

    def _handlePrint(self, payload):
        self._logger.info("Handling print download")
        self.canvas.downloadPrintFiles(payload["queuedPrint"])
        state_to_send_back = {
            "state": {
                "reported": {
                    "queuedPrint": None
                },
                "desired": {
                    "queuedPrint": None
                }
            }
        }
        self._myDeviceShadow.shadowUpdate(json.dumps(state_to_send_back),
                                          self._onUpdate, 10)

    def _handleUserListChanges(self, payload):
        self._logger.info("Handling user list delta")
        current_yaml_users = list(
            self.canvas.hub_yaml["canvas-users"])  # for Python 2 & 3
        delta_users = payload["userIds"]

        # if contents are not the same, get new list of registered users
        if not set(current_yaml_users) == set(delta_users):
            self._logger.info(
                "Content not the same. Updating yaml user list first.")
            if len(delta_users) < len(current_yaml_users):
                removed_user = str(
                    set(current_yaml_users).difference(set(delta_users)).pop())
                self.canvas.removeUserFromYAML(removed_user)

        users_to_report = delta_users
        reportedState = {"state": {"reported": {"userIds": users_to_report}}}
        self._myDeviceShadow.shadowUpdate(json.dumps(reportedState),
                                          self._onUpdate, 10)
        # if there are no linked users, disconnect shadow client
        if not self.canvas.hub_yaml[
                "canvas-users"] and self.canvas.aws_connection:
            self._myShadowClient.disconnect()

    def _handleChanges(self, payload):
        if "userIds" in payload:
            self._handleUserListChanges(payload)
        if "queuedPrint" in payload:
            self._handlePrint(payload)

    # CALLBACKS

    def _onGetShadowObj(self, payload, responseStatus, token):
        self._logger.info("GOT SHADOW OBJECT")
        payload = json.loads(payload)
        if responseStatus == "accepted" and "delta" in payload["state"]:
            delta = payload["state"]["delta"]
            self._handleChanges(delta)
        else:
            self._logger.info("No delta found in object. No action needed.")

    def _onDelta(self, payload, responseStatus, token):
        self._logger.info("RECEIVED DELTA")
        payload = json.loads(payload)
        self._handleChanges(payload["state"])

    def _onUpdate(self, payload, responseStatus, token):
        self._logger.info("SHADOW UPDATE RESPONSE")

    def _onOnline(self):
        self._logger.info("Shadow client is online")
        self.canvas.aws_connection = True
        self.canvas.checkAWSConnection()
        self._connectThreadStop = True

    def _onOffline(self):
        self._logger.info("Shadow client is offline")
        self.canvas.aws_connection = False
        self.canvas.checkAWSConnection()

    ##############
    # PUBLIC
    ##############

    def connect(self):
        self._startConnectThread()

    def getData(self):
        self._myDeviceShadow.shadowGet(self._onGetShadowObj, 10)

    def disconnect(self):
        self._myShadowClient.disconnect()
Пример #23
0
# host = "a2xz6bh1uzu45m-ats.iot.us-west-2.amazonaws.com"
# certPath = "/home/pi/certs_east/certs_true/"
# clientId = "masterproject"
# thingName = "masterproject"
certPath = "/home/pi/certs_east/"
host = "a1ii3qlfr1qukw-ats.iot.us-east-1.amazonaws.com"
clientId = "iot295b_thing"
topic = "iot/temperature"
thingName = "iot295b_thing"

filename = "/home/pi/iotproject/aws-iot-device-sdk-python/cmpe295/pulse_reading.txt"
filename2 = "/home/pi/iotproject/aws-iot-device-sdk-python/cmpe295/temp_reading.txt"

myAWSIoTMQTTShadowClient = None
myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(clientId)
myAWSIoTMQTTShadowClient.configureEndpoint(host, 8883)
myAWSIoTMQTTShadowClient.configureCredentials(
    "{}Amazon-root-CA-1.pem".format(certPath),
    "{}private.pem.key".format(certPath), "{}device.pem.crt".format(certPath))

myAWSIoTMQTTShadowClient.configureAutoReconnectBackoffTime(1, 32, 20)
myAWSIoTMQTTShadowClient.configureConnectDisconnectTimeout(10)
myAWSIoTMQTTShadowClient.configureMQTTOperationTimeout(5)

myAWSIoTMQTTShadowClient.connect()

deviceShadowHandler = myAWSIoTMQTTShadowClient.createShadowHandlerWithName(
    thingName, True)

deviceShadowHandler.shadowDelete(customShadowCallback_Delete, 5)
            print("Requested State: " + json.dumps(requested_state))
            current_status = json.loads(ent_center.get_status())
            for device in requested_state:
                if device == "television":
                    ent_center.set_television_status(television_state=requested_state[device])
                elif device == "receiver":
                    ent_center.set_receiver_status(receiver_state=requested_state[device])
                else:
                    print("Unknown device %s in state" % device)
        update_shadow(self.shadowInstance, ent_center.get_status(), request_counter)

iot_tv_config = {}
with open('/etc/iot-tv/iot-tv.config') as conf:
    iot_tv_config = json.load(conf)
iot_client = AWSIoTMQTTShadowClient(iot_tv_config['shadowClient'])
iot_client.configureEndpoint(iot_tv_config['endpointHost'], iot_tv_config['endpointPort'])
cert_path = iot_tv_config['certPath']
root_cert = iot_tv_config['rootCACert']
cert_prefix = iot_tv_config['certPrefix']
iot_client.configureCredentials("%s/%s" % (cert_path, root_cert),
                                "%s/%s-private.pem.key" % (cert_path, cert_prefix),
                                "%s/%s-certificate.pem.crt" % (cert_path, cert_prefix))
iot_client.connect()

iot_handler = iot_client.createShadowHandlerWithName(iot_tv_config['shadowClient'], True)
iot_container_bot = callbackContainer(iot_handler)

ent_center = EntCenter.EntertainmentCenter(iot_tv_config)

last_status = ent_center.get_status()
update_shadow(iot_handler, last_status)
Пример #25
0
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTShadowClient
import logging
import time
import json
import RPi.GPIO as GPIO

BUTTONPIN = 18
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)  # Ignore warning for now
GPIO.setup(BUTTONPIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)

clientId = "mypythoncodebutton"
thingName = "LED"
isOn = False
myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(clientId)
myAWSIoTMQTTShadowClient.configureEndpoint(
    "a2c6vtfn7g8m57-ats.iot.us-east-1.amazonaws.com", 8883)
myAWSIoTMQTTShadowClient.configureCredentials("root-CA.pem",
                                              "LED-private.pem.key",
                                              "LED.pem.crt")

# Connect to AWS IoT
myAWSIoTMQTTShadowClient.connect()

deviceShadowHandler = myAWSIoTMQTTShadowClient.createShadowHandlerWithName(
    thingName, True)

# Loop forever
while True:  # Run forever
    input_state = GPIO.input(BUTTONPIN)
    if input_state == False:
        if isOn == False:
Пример #26
0
            time.sleep(ROTARYDELTA)


# Initialize the hardware and variables
LIGHTDELTA = 4
SOUNDDELTA = 4
ULTRADELTA = 4
ROTARYDELTA = 4
sound_status = 1
light_status = 1
rotary_status = 1
ultra_status = 1

# set up AWS IoT certificate-based connection
MY_MQTT_SHADOW_CLIENT = AWSIoTMQTTShadowClient(iot_thing_name)
MY_MQTT_SHADOW_CLIENT.configureEndpoint(iot_endpoint, 8883)
MY_MQTT_SHADOW_CLIENT.configureCredentials(ca, key, crt)
MY_MQTT_SHADOW_CLIENT.configureAutoReconnectBackoffTime(1, 32, 20)
MY_MQTT_SHADOW_CLIENT.configureConnectDisconnectTimeout(10)  # 10 sec
MY_MQTT_SHADOW_CLIENT.configureMQTTOperationTimeout(5)  # 5 sec
MY_MQTT_SHADOW_CLIENT.connect()
DEVICESHADOWHANDLER = MY_MQTT_SHADOW_CLIENT.createShadowHandlerWithName(
    iot_thing_name, True)
DEVICESHADOWHANDLER.shadowRegisterDeltaCallback(custom_shadow_callback_delta)

# do our initial report that the light is off
LASTREPORTTIME = datetime.datetime.utcnow()

t = threading.Thread(target=soundControl)
t.start()
t1 = threading.Thread(target=lightControl)
Пример #27
0
#Import SDK packages
import json

from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTShadowClient

#for cert based connection
myShadowClient = AWSIoTMQTTShadowClient("raspberry-pi")

myShadowClient.configureEndpoint("a1xugslbalqdxo.iot.us-east-1.amazonaws.com", 8883)

myShadowClient.configureCredentials("/home/pi/python_mqtt/aws-iot-certs/rootCA.pem.crt",
                                    "/home/pi/python_mqtt/aws-iot-certs/c6417d9f55-private.pem.key",
                                    "/home/pi/python_mqtt/aws-iot-certs/c6417d9f55-certificate.pem.crt")

#myShadowClient.configureConnectionDisconnectTimeout(10)
myShadowClient.configureMQTTOperationTimeout(5)

myShadowClient.connect()
myDeviceShadow = myShadowClient.createShadowHandlerWithName("Bot", True)

payload = json.dumps({
    "state":{
        "reported": {
            "this_thing_is_alive": "I am Raspberry"
            }
        }
    })

#myDeviceShadow.shadowGet(customCallback, 5)
#myDeviceShadow.shadowUpdate(payload, shadowUpdate, 5)
Пример #28
0
import spidev
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTShadowClient

spi = spidev.SpiDev()
spi.open(0, 0)
spi.max_speed_hz = 1350000

Client_ID = "IoT_System_Client"
Thing_Name = "raspberrypi6"
Host_Name = "azjctapxbp7sc-ats.iot.us-east-2.amazonaws.com"
Root_CA = "/home/pi/certification/RootCA.crt"
Private_Key = "/home/pi/certification/a75d9d3b12-private.pem.key"
Cert_File = "/home/pi/certification/a75d9d3b12-certificate.pem.crt"

Client = AWSIoTMQTTShadowClient(Client_ID)
Client.configureEndpoint(Host_Name, 8883)
Client.configureCredentials(Root_CA, Private_Key, Cert_File)
Client.configureConnectDisconnectTimeout(10)
Client.configureMQTTOperationTimeout(5)
Client.connect()

Device = Client.createShadowHandlerWithName(Thing_Name, True)


def Callback_func(payload, responseStatus, token):
    print()
    print('UPDATE: $aws/things/' + Thing_Name + '/shadow/update/#')
    print("payload = " + payload)
    print("responseStatus = " + responseStatus)
    print("token = " + token)
Пример #29
0
os.system(' mkdir live')

mac = get_mac()
print (mac)
s3 = boto3.client('s3', aws_access_key_id= open('keys.txt').readline().split(None, 1)[0],
aws_secret_access_key= open('keys.txt').readlines()[1].split(None, 1)[0])

s3.download_file('littercam','device-'+str(mac)+'/devicename.txt', 'devicename.txt')
devicename = open('devicename.txt').readline().split(None, 1)[0]


print(devicename)

ShadowClient = AWSIoTMQTTShadowClient("")

ShadowClient.configureEndpoint("a1oa9tg9lcso0.iot.eu-west-1.amazonaws.com", 8883)
ShadowClient.configureCredentials(get_rootca(),
get_private(),get_cert())
ShadowClient.configureAutoReconnectBackoffTime(1, 32, 20)
ShadowClient.configureConnectDisconnectTimeout(30)  # 10 sec
ShadowClient.configureMQTTOperationTimeout(10)  # 5 sec
ShadowClient.connect()
deviceShadowHandler = ShadowClient.createShadowHandlerWithName(devicename, True)
#shadowCallbackContainer_Bot = shadowCallbackContainer(deviceShadowHandler)
#deviceShadowHandler.shadowRegisterDeltaCallback(shadowCallbackContainer_Bot.customShadowCallback_Delta)




# MQTT Connection establishement
myMQTTClient = AWSIoTMQTTClient(devicename)
Пример #30
0
        description='Web Greengrass Device',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('config_file', help="The config file.")
    parser.add_argument('--debug',
                        default=False,
                        action='store_true',
                        help="Activate debug output.")
    args = parser.parse_args()

    try:
        cfg = GroupConfigFile(args.config_file)

        web_name = cfg['devices']['GGD_web']['thing_name']
        # get a shadow client to receive commands
        mqttc_shadow_client = AWSIoTMQTTShadowClient(web_name)
        mqttc_shadow_client.configureEndpoint(ggd_config.master_core_ip,
                                              ggd_config.master_core_port)
        mqttc_shadow_client.configureCredentials(
            CAFilePath=dir_path + "/certs/master-server.crt",
            KeyPath=dir_path + "/certs/GGD_web.private.key",
            CertificatePath=dir_path + "/certs/GGD_web.certificate.pem.crt")

        if not mqtt_connect(mqttc_shadow_client):
            raise EnvironmentError("connection to Master Shadow failed.")

        mqttc = mqttc_shadow_client.getMQTTConnection()

        # create and register the shadow handler on delta topics for commands
        global master_shadow
        master_shadow = mqttc_shadow_client.createShadowHandlerWithName(
            "MasterBrain",
            True)  # persistent connection with Master Core shadow
class ThermoSimAppGUI:

    _usage = """Usage:

    Make sure that you put all your credentials under: ./certs/
    with the following naming conventions:
    Root CA file: *CA.crt
    Certificate file (not required if using MQTT over WebSocket): *.pem.crt
    Private key file (not required if using MQTT over WebSocket): *.pem.key

    Use X.509 certificate based mutual authentication:
    python ThermostatSimulatorApp -e <endpoint>

    Use MQTT over WebSocket:
    python ThermostatSimulatorApp -e <endpoint> -w

    Type "python ThermostatSimulatorApp -h" for detailed command line options.


    """

    _helpInfo = """Available command line options:
    -e, --endpoint: Your custom AWS IoT custom endpoint
    -w, --websocket: Use MQTT over websocket
    -h, --help: Help infomation


    """

    def __init__(self):
        # Init data members
        # Connection related
        self._endpoint = ""
        self._rootCAFilePathList = ""
        self._certificateFilePathList = ""
        self._privateKeyFilePathList = ""
        self._useWebsocket = False
        self._AWSIoTMQTTShadowClient = None
        self._thermostatSimulatorShadowHandler = None
        # GUI related
        self._tkRootHandler = tkinter.Tk()
        self._reportedDataVariable = None
        self._reportedDataDisplayBox = None
        self._desiredDataVariable = None
        self._desiredDataDisplayBox = None
        self._setTemperatureInputBox = None
        self._setTemperatureButton = None
        # Check command line inputs
        if not self._checkInputs():
            raise ValueError("Malformed/Missing command line inputs.")
        # Create and configure AWSIoTMQTTShadowClient
        self._AWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient("ThermostatSimulatorApp", useWebsocket=self._useWebsocket)
        if self._useWebsocket:
            self._AWSIoTMQTTShadowClient.configureEndpoint(self._endpoint, 443)
            self._AWSIoTMQTTShadowClient.configureCredentials(self._rootCAFilePathList[0])
        else:
            self._AWSIoTMQTTShadowClient.configureEndpoint(self._endpoint, 8883)
            self._AWSIoTMQTTShadowClient.configureCredentials(self._rootCAFilePathList[0], self._privateKeyFilePathList[0], self._certificateFilePathList[0])
        self._AWSIoTMQTTShadowClient.configureAutoReconnectBackoffTime(1, 128, 20)
        self._AWSIoTMQTTShadowClient.configureConnectDisconnectTimeout(10)
        self._AWSIoTMQTTShadowClient.configureMQTTOperationTimeout(5)
        # Set keepAlive interval to be 1 second and connect
        # Raise exception if there is an error in connecting to AWS IoT
        self._AWSIoTMQTTShadowClient.connect(5)
        self._thermostatSimulatorShadowHandler = self._AWSIoTMQTTShadowClient.createShadowHandlerWithName("room", True)
        # Generate GUI
        self._packModule()

    # Validate command line inputs
    # Return False there is any malformed inputs
    # Return True if all the necessary inputs have been discovered
    def _checkInputs(self):
        gotEoughInputs = True
        # Check command line inputs
        try:
            opts, args = getopt.getopt(sys.argv[1:], "hwe:", ["endpoint=", "websocket", "help"])
            if len(opts) == 0:
                raise getopt.GetoptError("No input parameters")
            for opt, arg in opts:
                if opt in ("-e", "--endpoint"):
                    self._endpoint = arg
                if opt in ("-w", "--websocket"):
                    self._useWebsocket = True
                if opt in ("-h", "--help"):
                    print(self._helpInfo)
                    gotEoughInputs = False
        except getopt.GetoptError:
            print(self._usage)
            gotEoughInputs = False
        # Check credential files
        if gotEoughInputs:
            self._rootCAFilePathList = glob.glob("./certs/*CA.crt")
            if self._useWebsocket:
                gotEoughInputs = gotEoughInputs and len(self._rootCAFilePathList) != 0
                if not gotEoughInputs:
                    print("Missing rootCA in ./certs/")
            else:
                self._certificateFilePathList = glob.glob("./certs/*.pem.crt")
                self._privateKeyFilePathList = glob.glob("./certs/*.pem.key")
                gotEoughInputs = gotEoughInputs and len(self._rootCAFilePathList) != 0 and len(self._certificateFilePathList) != 0 and len(self._privateKeyFilePathList) != 0
                if not gotEoughInputs:
                    print("Missing rootCA, certificate or private key in ./certs/")
        return gotEoughInputs

    def _packModule(self):
        self._tkRootHandler.title("ThermostatSimulatorApp")
        self._tkRootHandler.geometry("500x250")
        self._tkRootHandler.resizable(width=False, height=False)
        # Pack all frames
        baseFrame = tkinter.Frame(self._tkRootHandler)
        temperatureFrame = tkinter.Frame(baseFrame)
        temperatureFrame.pack(side="top")
        controlPanelFrame = tkinter.Frame(baseFrame)
        controlPanelFrame.pack(side="bottom")
        baseFrame.pack()
        # Pack all modules for temperature frame
        self._reportedDataVariable = tkinter.StringVar()
        self._reportedDataVariable.set("XX.X F")
        reportedDataTag = tkinter.Label(temperatureFrame, text="Reported Temperature:", justify="left")
        self._reportedDataDisplayBox = tkinter.Label(temperatureFrame, textvariable=self._reportedDataVariable, font=("Arial", 55), justify="left")
        #
        self._desiredDataVariable = tkinter.StringVar()
        self._desiredDataVariable.set("XX.X F")
        desiredDataTag = tkinter.Label(temperatureFrame, text="Desired Temperature:", justify="left")
        self._desiredDataDisplayBox = tkinter.Label(temperatureFrame, textvariable=self._desiredDataVariable, font=("Arial", 55), justify="left")
        #
        reportedDataTag.pack()
        self._reportedDataDisplayBox.pack()
        desiredDataTag.pack()
        self._desiredDataDisplayBox.pack()
        # Create a callback pool
        self._callbackPoolHandler = ThermoSimAppCallbackPool(self._tkRootHandler, self._reportedDataDisplayBox, self._thermostatSimulatorShadowHandler, self._reportedDataVariable, self._desiredDataVariable)
        # Pack all modules for control panel frame
        self._setTemperatureInputBox = tkinter.Entry(controlPanelFrame)
        self._setTemperatureInputBox.pack(sid="left")
        self._setTemperatureButton = tkinter.Button(controlPanelFrame, text="SET", command=lambda: self._callbackPoolHandler.buttonCallback(self._setTemperatureInputBox, self._desiredDataVariable))
        self._setTemperatureButton.pack()

    def runApp(self):
        # Start and run the app
        self._tkRootHandler.after(500, self._callbackPoolHandler.sendShadowGetForReportedTemperature)  # per 500ms
        self._tkRootHandler.after(500, self._callbackPoolHandler.updateReportedTemperatureDataVariable)  # per 500ms
        self._tkRootHandler.mainloop()
Пример #32
0
    deviceShadowHandler.shadowUpdate(json.dumps(jsonPayload),
                                     customShadowCallback_upate, 50)


sense = SenseHat()

# aws iot info
awsiotHost = "a1eeyktzyeh5hs-ats.iot.us-east-1.amazonaws.com"
awsiotPort = 443
rootCAPath = "/home/pi/Scripts/lab3/crt/root-ca-cert.pem"
privateKeyPath = "/home/pi/Scripts/lab3/crt/ac354bff74-private.pem.key"
certificatePath = "/home/pi/Scripts/lab3/crt/ac354bff74-certificate.pem.crt"

myAWSIoTMQTTShadowClient = None
myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient("Actuator")
myAWSIoTMQTTShadowClient.configureEndpoint(awsiotHost, awsiotPort)
myAWSIoTMQTTShadowClient.configureCredentials(rootCAPath, privateKeyPath,
                                              certificatePath)

myAWSIoTMQTTShadowClient.configureAutoReconnectBackoffTime(1, 32, 20)
myAWSIoTMQTTShadowClient.configureConnectDisconnectTimeout(60)  # 10sec
myAWSIoTMQTTShadowClient.configureMQTTOperationTimeout(30)  #5sec

#connect to AWS IoT
myAWSIoTMQTTShadowClient.connect()

#create a devcie Shadow with persistent subscription
thingName = "my-iot-thing"
deviceShadowHandler = myAWSIoTMQTTShadowClient.createShadowHandlerWithName(
    thingName, True)
	parser.error("Missing credentials for authentication.")
	exit(2)

# Configure logging
logger = logging.getLogger("AWSIoTPythonSDK.core")
logger.setLevel(logging.DEBUG)
streamHandler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
streamHandler.setFormatter(formatter)
logger.addHandler(streamHandler)

# Init AWSIoTMQTTShadowClient
myAWSIoTMQTTShadowClient = None
if useWebsocket:
	myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(clientId, useWebsocket=True)
	myAWSIoTMQTTShadowClient.configureEndpoint(host, 443)
	myAWSIoTMQTTShadowClient.configureCredentials(rootCAPath)
else:
	myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(clientId)
	myAWSIoTMQTTShadowClient.configureEndpoint(host, 8883)
	myAWSIoTMQTTShadowClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath)

# AWSIoTMQTTShadowClient configuration
myAWSIoTMQTTShadowClient.configureAutoReconnectBackoffTime(1, 32, 20)
myAWSIoTMQTTShadowClient.configureConnectDisconnectTimeout(10)  # 10 sec
myAWSIoTMQTTShadowClient.configureMQTTOperationTimeout(5)  # 5 sec

# Connect to AWS IoT
myAWSIoTMQTTShadowClient.connect()

# Create a deviceShadow with persistent subscription
Пример #34
0
class AwsProvider(metaclass=Singleton):
    __config = {}
    __client = None
    __shadow = None
    __shadowHandle = None
    __instance = None

    def __init__(self, config):
        self.__config = config
        logger.debug("Initialising AWS Provider...")
        self.__init_shadow()

    def __init_client(self):
        self.__client = AWSIoTMQTTClient(self.__config["aws"]["client_id"])
        try:
            self.__client.configureEndpoint(self.__config["aws"]["endpoint"],
                                            self.__config["aws"]["port"])
            logger.info("Trying to connect to {}:{}".format(
                self.__config["aws"]["endpoint"],
                self.__config["aws"]["port"]))
            self.__client.configureCredentials(self.__config["aws"]["root"],
                                               self.__config["aws"]["private"],
                                               self.__config["aws"]["cert"])

            # Infinite offline Publish queueing
            self.__client.configureOfflinePublishQueueing(-1)
            self.__client.configureDrainingFrequency(2)  # Draining: 2 Hz
            self.__client.configureConnectDisconnectTimeout(10)  # 10 sec
            self.__client.configureMQTTOperationTimeout(5)  # 5 sec

            self.__client.connect()
        except AWSIoTExceptions.connectTimeoutException as error:
            logger.error("Problem with MQTT configuration: {}".format(error))
        logger.debug("Initialised AWS Standard Client...")

    def __init_shadow(self):
        self.__shadow = AWSIoTMQTTShadowClient(
            self.__config["aws"]["client_id"] + "_shadow")
        try:
            self.__shadow.configureEndpoint(self.__config["aws"]["endpoint"],
                                            self.__config["aws"]["port"])
            logger.info("Trying to connect to {}:{}".format(
                self.__config["aws"]["endpoint"],
                self.__config["aws"]["port"]))
            self.__shadow.configureCredentials(self.__config["aws"]["root"],
                                               self.__config["aws"]["private"],
                                               self.__config["aws"]["cert"])

            # Infinite offline Publish queueing
            self.__shadow.configureAutoReconnectBackoffTime(1, 32, 20)
            self.__shadow.configureConnectDisconnectTimeout(10)  # 10 sec
            self.__shadow.configureMQTTOperationTimeout(5)  # 5 sec

            self.__shadow.connect()
            self.__shadowHandle = self.__shadow.createShadowHandlerWithName(
                self.__config["aws"]["thing_id"], True)
        except AWSIoTExceptions.connectTimeoutException as error:
            logger.error("Problem with MQTT configuration: {}".format(error))
        logger.debug("Initialised AWS Standard Client...")

    def get_client(self):
        if self.__client is None:
            self.__init_client()
        return self.__client

    def get_shadow_handle(self):
        if self.__shadowHandle is None:
            self.__init_shadow()

        return self.__shadowHandle