· 5 years ago · Feb 09, 2021, 04:38 PM
1from __future__ import print_function
2import paho.mqtt.publish as publish
3import psutil
4import string
5import random
6import time
7from datetime import datetime
8
9string.alphanum = '1234567890avcdefghijklmnopqrstuvwxyzxABCDEFGHIJKLMNOPQRSTUVWXYZ'
10# Replace <YOUR-CHANNEL-ID> with your channel ID.
11channelID = "1301242"
12# Replace <YOUR-CHANNEL-WRITEAPIKEY> with your write API key.
13writeAPIKey = "TL7LVPPDXRXOFGXG"
14# The hostname of the ThingSpeak MQTT broker.
15mqttHost = "mqtt.thingspeak.com"
16# You can use any username.
17mqttUsername = "mwa0000021483824"
18# Your MQTT API key from Account > My Profile.
19mqttAPIKey = "MVALKEH208WOKAHE"
20
21tTransport = "websockets"
22tPort = 80
23# Create the topic string.
24topic = "channels/" + channelID + "/publish/" + writeAPIKey
25
26cont = 0
27while(cont<5):
28 clientID = ''
29 cont += 1
30
31 for x in range(1,16):
32 clientID += random.choice(string.alphanum)
33
34 # get data
35 date = datetime.now().strftime("%d/%m/%Y-%H:%M:%S")
36 ph = round(random.uniform(1,15),2)
37 temp = round(random.uniform(0,45),2)
38 aux = [random.choice(string.alphanum) for i in range(10)]
39 text = ""
40 for c in aux:
41 text += c
42
43 ## monta o payload
44 payload = "field1=" + str(date) + \
45 "&field2=" + str(ph) + \
46 "&field3=" + str(temp) + \
47 "&field4=" + str(text)
48
49 try:
50 publish.single(topic,
51 payload,
52 hostname=mqttHost,
53 transport=tTransport,
54 port=tPort,
55 auth={'username':mqttUsername,'password':mqttAPIKey}
56 )
57 print(cont, "# sending data...")
58 except Exception as e:
59 print ("error: ", e)
60
61 time.sleep(30)