def main(): # Cayenne authentication info MQTT_USERNAME = "******" MQTT_PASSWORD = "******" MQTT_CLIENT_ID = "cd803190-47fd-11ea-84bb-8f71124cfdfb" client = cayenne.client.CayenneMQTTClient() client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID) # Initialise all variables starttime = time.time() temp, hum, nh3, no2, light, proxim, pressure, curTime = output() oldTemp, oldHum, oldNh3, oldNo2, oldLight, oldProxim, oldPressure = temp, hum, nh3, no2, light, proxim, pressure while True: # Send values to Cayenne client.loop() client.celsiusWrite(1, temp) client.virtualWrite(2, hum) client.virtualWrite(3, no2) client.virtualWrite(4, nh3) client.luxWrite(5, light) # client.virtualWrite(6, proxim) # Filter inaccurate pressure readings if (pressure < 700): client.virtualWrite(7, oldPressure) else: client.virtualWrite(7, pressure) oldPressure = pressure save() # Calculate how long the program has been running for timeDiff = time.localtime(time.time() - starttime - 3600) runTime = time.strftime("%H:%M", timeDiff) display(light, curTime, runTime) # Have the program send values once every minute time.sleep(60.0 - ((time.time() - starttime) % 60.0)) # Update values oldTemp, oldHum, oldNh3, oldNo2, oldLight, oldProxim = temp, hum, nh3, no2, light, proxim temp, hum, nh3, no2, light, proxim, pressure, curTime = output()
#!/usr/bin/env python import cayenne.client import time import logging # Cayenne authentication info. This should be obtained from the Cayenne Dashboard. MQTT_USERNAME = "******" MQTT_PASSWORD = "******" MQTT_CLIENT_ID = "CAYENNE_CLIENT_ID" client = cayenne.client.CayenneMQTTClient() client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID, loglevel=logging.INFO) # For a secure connection use port 8883 when calling client.begin: # client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID, port=8883, loglevel=logging.INFO) i=0 timestamp = 0 while True: client.loop() if (time.time() > timestamp + 10): client.celsiusWrite(1, i) client.luxWrite(2, i*10) client.hectoPascalWrite(3, i+800) timestamp = time.time() i = i+1
last_alert_timestamp = time.time() # end of while(True) else: # check for cayenne publish or commands client.loop() time.sleep(0.1) current = {} client = cayenne.client.CayenneMQTTClient() client.on_message = on_message client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID) # For a secure connection use port 8883 when calling client.begin: # client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID, port=8883) q = Queue.Queue(1) t1 = threading.Thread(target=produceData) t1.start() if __name__ == "__main__": #HOST, PORT = "localhost", 9999 HOST, PORT = "0.0.0.0", 9999 # Create the server, binding to localhost on port 9999 for i in range(0,50): try: server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
import cayenne.client import datetime import time import requests import serial import logging # Cayenne authentication info. This should be obtained from the Cayenne Dashboard. MQTT_USERNAME = "" MQTT_PASSWORD = "" MQTT_CLIENT_ID = "" client = cayenne.client.CayenneMQTTClient() client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID, port=8883) i = 0 timestamp = 0 ser = serial.Serial(port='/dev/ttyUSB0', baudrate=115200, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS) #Start Fresh ser.flushOutput() ser.flushInput() # Accuweather data API_KEY = "" LOCATION_KEY = "2094707" API_URL = "https://dataservice.accuweather.com/currentconditions/v1/"
#!/usr/bin/env python import cayenne.client # Cayenne authentication info. This should be obtained from the Cayenne Dashboard. MQTT_USERNAME = "******" MQTT_PASSWORD = "******" MQTT_CLIENT_ID = "MQTT_CLIENT_ID" # The callback for when a message is received from Cayenne. def on_message(message): print("message received: " + str(message)) # If there is an error processing the message return an error string, otherwise return nothing. client = cayenne.client.CayenneMQTTClient() client.on_message = on_message client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID) client.loop_forever()
def configureCayenne(MQTT_USRNAME="", MQTT_PASS="", MQTT_CLNT_ID=""): client = cayenne.client.CayenneMQTTClient() client.on_message = messageReceived client.begin(MQTT_USRNAME, MQTT_PASS, MQTT_CLNT_ID) return client
# The callback for when a message is received from Cayenne. def on_message(message): print('message received: ' + str(message)) if __name__ == '__main__': config = configparser.ConfigParser() config.read(config_path) mqtt_username = config['mqtt']['username'] mqtt_password = config['mqtt']['password'] mqtt_client_id = config['mqtt']['client_id'] client = cayenne.client.CayenneMQTTClient() client.on_message = on_message client.begin(mqtt_username, mqtt_password, mqtt_client_id) updateLast = 0 i = 1 loopStart = time.time() while ((time.time() - loopStart) < 60): client.loop() if ((time.time() - updateLast) > updateInterval): client.virtualWrite(1, i, 'null', 'd') # client.virtualWrite(2, i) # client.virtualWrite(3, i) # client.virtualWrite(4, i)
# name and sequence of data sensor_parameter = [ "air_temperature", "air_humidity", "soil_temperature", "soil_humidity", "luminance" ] # init data array sensor_data_panda = pandas.DataFrame(columns=sensor_parameter) # number of samples to record numberOfRecordings = 20 sampleNum = 0 client = cayenne.client.CayenneMQTTClient() client.on_message = on_message client.begin(config.MQTT_USERNAME, config.MQTT_PASSWORD, config.MQTT_CLIENT_ID) # For a secure connection use port 8883 when calling client.begin: # client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID, port=8883) while True: # try: # read serial byte data sensor_data_raw = ser.readline() # convert byte data to UTF string sensor_data_str = sensor_data_raw[0:len(sensor_data_raw) - 2].decode("utf-8") # convert UTF string to array sensor_data_arr = sensor_data_str.split(",") # length fits to parameter names, parse and store if len(sensor_data_arr) == len(sensor_parameter):
#!/usr/bin/env python import cayenne.client import time import logging from gps3 import gps3 # Cayenne authentication info. This should be obtained from the Cayenne Dashboard. MQTT_USERNAME = "******" MQTT_PASSWORD = "******" MQTT_CLIENT_ID = "CLIENTID" client = cayenne.client.CayenneMQTTClient() client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID, 'mqtt.mydevices.com') # For a secure connection use port 8883 when calling client.begin: # client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID, port=8883, loglevel=logging.INFO) gps_socket = gps3.GPSDSocket() data_stream = gps3.DataStream() gps_socket.connect() gps_socket.watch() for new_data in gps_socket: if new_data: data_stream.unpack(new_data) client.loop() client.virtualWrite( 1, str(data_stream.TPV['lat']) + "," + str(data_stream.TPV['lon']) + "," + str(data_stream.TPV['alt']), "gps", "m") time.sleep(10)
def on_message(client, userData, message): # based on https://developers.mydevices.com/cayenne/docs/cayenne-mqtt-api/#cayenne-mqtt-api-mqtt-messaging-topics-send-actuator-updated-value print("message received: ", str(message.payload.decode("utf-8"))) def on_connect(client, userData, flags, rc): print("Connected with result code " + str(rc)) # Connect to Cayenne Cloud client = cayenne.client.CayenneMQTTClient() client.on_message = on_message client.on_connect = on_connect client.begin(CayenneParam.get('CayUsername'), \ CayenneParam.get('CayPassword'), \ CayenneParam.get('CayClientID'), \ ) CheckingQueue = True while CheckingQueue: CayQueue = Queue(QueuePathFile, autosave=True) if not (CayQueue.empty()): CayPacket = CayQueue.get() Save2CSV (CSVPath, \ CayPacket['CayClientID'], \ CayPacket['Channel'], \ CayPacket['Data'] \
def ProcessError(CSVPath, ClientID, CayClient, CSV_Message, Message): # Save Message to a file and Cayenne global LastError CurrentTime = datetime.datetime.now().isoformat() CSVPathFile = Save2CSV (CSVPath, ClientID, 'Exception', CSV_Message) CurrentTime = datetime.datetime.now().isoformat() LogPathFile = logging.getLoggerClass().root.handlers[0].baseFilename # Connect to Cayenne Cloud client = cayenne.client.CayenneMQTTClient() client.on_message = on_message client.on_connect = on_connect client.begin(MQTTCreds.get('MQTTUsername'), \ MQTTCreds.get('MQTTPassWord'), \ MQTTCreds.get('MQTTClientID'), \ ) Thresholds = ConfigDict.get('DetectionThresholds') # loglevel=logging.INFO) # Logging doesn't seem to work in Python3 # For a secure connection use port 8883 when calling client.begin: # client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID, port=8883, loglevel=logging.INFO) SerialListen = True # Save2Cayenne (client, 'Z', '123>') # Random experiement (didn't work) try: while SerialListen: with serial.Serial(SERIAL_PORT, BAUDRATE) as ser: # Data processing # if DRF126x: # PacketIn = ser.read(8)
# Create dictionary to store channel divisors DivisorDict = ConfigDict.get('ChannelDivisors') # Create Dictionary to store offset values OffsetDict = ConfigDict.get('OffsetValues') #This sets up the serial port specified above. baud rate is the bits per second timeout seconds #port = serial.Serial(SERIAL_PORT, baudrate=2400, timeout=5) #This sets up the serial port specified above. baud rate and WAITS for any cr/lf (new blob of data from picaxe) port = serial.Serial(SERIAL_PORT, baudrate=2400) client = cayenne.client.CayenneMQTTClient() client.begin(MQTTCreds.get('CayUsername'), \ MQTTCreds.get('CayPassword'), \ MQTTCreds.get('CayClientID')) LastCheckPeng = time.time() # loglevel=logging.INFO) # For a secure connection use port 8883 when calling client.begin: # client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID, port=8883, loglevel=logging.INFO) error=123 while True: try: # The file compares the date when the file was last checked if date.today() > LastCheckFile: # if the file hasn't been check today, the file will be reloaded into the variables
try: done = False # The callback for when a message is received from Cayenne. def on_message(message): if message.msg_id == "senderror": # Test sending an error string. return "error response" if message.msg_id == "done": #The "done" message should be the last message so we set the done flag global done done = True client = cayenne.client.CayenneMQTTClient() client.on_message = on_message client.begin(args.username, args.password, args.clientID, args.host, args.port) start = time.time() while not client.connected: client.loop() print("Test publishing data") client.virtualWrite(0, 0) client.celsiusWrite(1, 1) client.fahrenheitWrite(2, 2) client.kelvinWrite(3, 3) client.luxWrite(4, 4) client.pascalWrite(5, 5) client.hectoPascalWrite(6, 6) print("Test receiving commands") client.mqttPublish(client.rootTopic + '/cmd/10', 'senderror,0')