def Test_Profile(): if (x<Time_1): Gas_Servo.gas_prozent(Throttle_1) virtualWrite(21, frequence_Reader.RPM, "analog_actuator", "null") sleep(1) # time increases until it reaches Time 1 x += 1 if (x==Time_1 and y<Time_2): Gas_Servo.gas_prozent(Throttle_2) virtualWrite(22, frequence_Reader.RPM, "analog_actuator", "null") sleep(1) # time increases until it reaches Time 2 y += 1 if (x==Time_1 and y==Time_2 and z<Time_3): Gas_Servo.gas_prozent(Throttle_3) virtualWrite(23, frequence_Reader.RPM, "analog_actuator", "null") sleep(1) # time increases until it reaches Time 3 z += 1 # Throttle goes back to 0 after test profile is done and time out signal if (x==Time_1 and y==Time_2 and z=Time_3): Gas_Servo.move(Winkel_Gas_min) client.virtualWrite(30,1,"digital_sensor" , "d")
def uploadData(): client.loop() print(temp.name()) # Read the temperature ten times, printing both the Celsius and # equivalent Fahrenheit temperature, waiting one second between readings #for i in range(0, 10): celsius = temp.value() fahrenheit = celsius * 9.0 / 5.0 + 32.0 print("%d degrees Celsius, or %d degrees Fahrenheit" \ % (celsius, fahrenheit)) time.sleep(1) # Read values of the light sensor lightLux = light.value() print(light.name() + " raw value is %d" % light.raw_value() + \ ", which is roughly %d" % light.value() + " lux") time.sleep(1) # Wait for Ait quality sensor to warm up - it takes about 3 minutes print("Sensor is warming up for 3 minutes...") for i in range(1, 4): time.sleep(60) print(i, "minute(s) passed.") print("Sensor is ready!") # Read values of Air quality sensor airValue = airSensor.getSample() ppm = airSensor.getPPM() print("raw: %4d" % airValue, " ppm: %5.2f " % ppm, airQuality(airValue)) #Uploading data to Cayenne print("Uploading data to Cayenne ...") client.celsiusWrite(1, celsius) client.luxWrite(2, lightLux) client.virtualWrite(3, airValue)
def main(): print datetime.datetime.now() #Canadians do Celcius print ctrl.set_unit('f') i = 0 timestamp = 0 while True: #Cayenne kick client.loop() #Call every 10 seconds if (time.time() > timestamp + 10): #send the current temperature client.celsiusWrite(1, ctrl.read_temp()) #send the set temperature client.celsiusWrite(3, ctrl.send_command_async("read set temp")) #send the run status if (ctrl.anova_status() == 'stopped'): a_stat = 0 else: a_stat = 1 client.virtualWrite(2, a_stat) #save last timestamp timestamp = time.time()
def send_trigger_value(trigger_channel, sensor_value, threshold, send_below_threshold): global crossed_threshold if (((sensor_value >= threshold) and not send_below_threshold) or ((sensor_value < threshold) and send_below_threshold)): if not crossed_threshold: client.virtualWrite(trigger_channel, 1, "digital_sensor", "d") crossed_threshold = True else: client.virtualWrite(trigger_channel, 0, "digital_sensor", "d") crossed_threshold = False
def on_message(message): print("Message received: " + str(message)) #print("channel %s, topic %s, value %s" % (message.channel, message.topic, message.value)) # If there is an error processing the message return an error string, otherwise return nothing. #if (True): if (message["channel"]=="4") & (message["topic"]=="cmd"): light_state = message.value print("Set light to %s" % (message.value)) light.put_value(light_state) client.virtualWrite(4, light_state, dataType="digital_actuator", dataUnit="d") client.responseWrite(message.msg_id) client.loop()
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()
def Time_out(): global Connection_Timer # Timeout after 400 seconds client.virtualWrite(21, 1, "digital_sensor", "d") Connection_Timer = 0 print("Anlage aus") Gas_Servo.ausschalten() Chokehebel_fahren_Servo.ausschalten() Chokehebel_drehen_Servo.ausschalten() pi.write(Gas_Relais_GPIO, 0) pi.write(Chokehebel_fahren_Relais_GPIO, 0) pi.write(Chokehebel_drehen_Relais_GPIO, 0) Relais_Setup() Grundstellung() sleep(2) client.virtualWrite(21, 0, "digital_sensor", "d")
def data_received(self, data): print(len(data)) print(data) # decoding the message message = data.decode() print('Data received: {!r}'.format(message)) value = int(message) print('Data decoded: {}'.format(value)) # sending the message via MQQT # client.loop() channel = 1 client.virtualWrite(channel, value) # closing the client socket print('Close the client socket') self.transport.close()
def _cbf(self, gpio, level, tick): global Motor_an_Flag global Not_Aus_Flag global Kaltstart_Flag global Warmstart_Flag global Betrieb_Flag global Gas_Relais_GPIO global Chokehebel_fahren_Relais_GPIO global Chokehebel_drehen_Relais_GPIO #global Zustand #Not aus betaetigt if level == 0: Not_Aus_Flag = True Motor_an_Flag = False print( "Notaus betaetigt\n----------------WICHTIG----------------\nVor Loesen des Notaus Chokehebel auf 0 stellen!" ) Gas_Servo.ausschalten() Chokehebel_fahren_Servo.ausschalten() Chokehebel_drehen_Servo.ausschalten() pi.write(Gas_Relais_GPIO, 0) pi.write(Chokehebel_fahren_Relais_GPIO, 0) pi.write(Chokehebel_drehen_Relais_GPIO, 0) LED_off() client.virtualWrite(21, 1, "digital_sensor", "d") #Zustand = Zustaende.Aus Kaltstart_Flag = False client.virtualWrite(18, 0, "digital_sensor", "d") Warmstart_Flag = False client.virtualWrite(19, 0, "digital_sensor", "d") Betrieb_Flag = False client.virtualWrite(20, 0, "digital_sensor", "d") if level == 1: sleep(2) #Sichergehen dass die BewegungsThreads geschlossen sind client.virtualWrite(21, 0, "digital_sensor", "d") Relais_Setup() Grundstellung() Not_Aus_Flag = False print("Notaus geloest")
def Test_Profile(): global Time_1 global Time_2 global Time_3 global Throttle_1 global Throttle_2 global Throttle_3 global x global y global z if (x < Time_1): print('Throttle 1 running') Gas_Servo.gas_prozent(Throttle_1) # writing to RPM 1 cayenne #client.virtualWrite(22, frequence_Reader.RPM, "analog_actuator", "null") sleep(1) # time increases until it reaches Time 1 x += 1 print('Throttle 1 running ') if (x == Time_1 and y < Time_2): Gas_Servo.gas_prozent(Throttle_2) # writing to RPM 2 cayenne #client.virtualWrite(23, frequence_Reader.RPM, "analog_actuator", "null") # time increases until it reaches Time 2 y += 1 if (x == Time_1 and y == Time_2 and z < Time_3): Gas_Servo.gas_prozent(Throttle_3) # writing to RPM 3 cayenne #client.virtualWrite(24, frequence_Reader.RPM, "analog_actuator", "null") # time increases until it reaches Time 3 z += 1 # Throttle goes back to 0 after test profile is done and time out signal if (x == Time_1 and y == Time_2 and z == Time_3): Gas_Servo.move(Winkel_Gas_min) # writing to Throttle Timeout client.virtualWrite(30, 1, "digital_sensor", "d")
def on_message(message): global OnOff_Flag global MotorSaegeButton_Flag global KaltstartButton_Flag global WarmstartButton_Flag global BetriebButton_Flag global StartStopSignalButton_Flag global x if message.channel == 1: #channel for on/off button if message.value == "1": OnOff_Flag = True elif message.value == "0": OnOff_Flag = False elif message.channel == 2: #channel for MS if message.value == "1": MotorSaegeButton_Flag = True elif message.value == "0": MotorSaegeButton_Flag = False elif message.channel == 4: #channel for cold start button if message.value == "1": KaltstartButton_Flag = True elif message.value == "0": KaltstartButton_Flag = False client.virtualWrite(18, 0, "digital_sensor", "d") elif message.channel == 5: #channel for warm start button if message.value == "1": WarmstartButton_Flag = True elif message.value == "0": WarmstartButton_Flag = False client.virtualWrite(19, 0, "digital_sensor", "d") elif message.channel == 6: #channel for betrieb button if message.value == "1": BetriebButton_Flag = True elif message.value == "0": BetriebButton_Flag = False client.virtualWrite(20, 0, "digital_sensor", "d") elif message.channel == 7: #channel for start/stop button if message.value == "1": StartStopSignalButton_Flag = True elif message.value == "0": StartStopSignalButton_Flag = False elif message.channel == 9: x = message.value return x
#!/usr/bin/env python import cayenne.client import time # Cayenne authentication info. This should be obtained from the Cayenne Dashboard. MQTT_USERNAME = "******" MQTT_PASSWORD = "******" MQTT_CLIENT_ID = "4901b0a0-8b67-11e8-87b0-97a7dd91c15a" # 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) # For a secure connection use port 8883 when calling client.begin: # client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID, port=8883) a = 27 b = 80 timestamp = 0 while True: client.loop() if (time.time() > timestamp + 5): client.virtualWrite(23, a) client.virtualWrite(30, b) timestamp = time.time()
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) if i == 1: i = 0 else: i = 1 updateLast = time.time() time.sleep(0.1)
sensor_data_arr = sensor_data_str.split(",") # length fits to parameter names, parse and store if len(sensor_data_arr) == len(sensor_parameter): # parse sensor_data_dict = { sensor_parameter[i]: float(sensor_data_arr[i]) for i in range(len(sensor_parameter)) } # store sensor_data_panda = sensor_data_panda.append(sensor_data_dict, ignore_index=True) # upload readings to myDevices Cayenne client.loop() client.celsiusWrite(1, sensor_data_dict["air_temperature"]) client.virtualWrite(2, sensor_data_dict["air_humidity"], "rel_hum", "p") client.celsiusWrite(3, sensor_data_dict["soil_temperature"]) client.virtualWrite(4, sensor_data_dict["soil_humidity"], "res", "ohm") client.luxWrite(5, sensor_data_dict["luminance"]) clear_output() print(sensor_data_arr) else: clear_output() print(sensor_data_str) print("Sensor array length does match expected number of parameters.") # except: # print("Interrupt") # ser.close() # break ser.close()
def on_message(message): print("Mensaje recibido: " + str(message)) client = cayenne.client.CayenneMQTTClient() client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID) client.on_message = on_message ser = serial.Serial('/dev/ttyACM0', 9600, timeout=0.5) regex = re.compile("[0-9]{2}\.[0-9]{2}") while True: try: client.loop() data = ser.readline().decode('utf-8').rstrip() print(data) if "Temp" in data: # client.virtualWrite(1,str(datetime.datetime.now())+';') client.virtualWrite(1, regex.findall(str(data))[1] + "\n") if "Hum" in data: # client.celsiusWrite(2,str(datetime.datetime.now())+';') client.celsiusWrite(2, regex.findall(str(data))[0] + "\n") except KeyboardInterrupt: break time.sleep(15)
n1_longitude = 0 n1_vandientu = 0 n2_t = 0 n2_h = 0 n2_hdat = 0 n2_latitude = 0 n2_longitude = 0 n2_pH = 0 n2_maybom = 0 while True: client.loop() if (time.time() > timestamp0 + 2): #IN DU LIEU LEN WEBSERVER CAYENNE NODE 1 client.celsiusWrite(11, n1_t) client.virtualWrite(12, n1_h, TYPE_RELATIVE_HUMIDITY, UNIT_PERCENT) client.virtualWrite(13, n1_hdat, TYPE_RELATIVE_HUMIDITY, UNIT_PERCENT) client.virtualWrite(14, n1_latitude) client.virtualWrite(15, n1_longitude) client.virtualWrite(17, n1_vandientu) #IN DU LIEU LEN WEBSERVER CAYENNE NODE 2 client.celsiusWrite(21, n2_t) client.virtualWrite(22, n2_h, TYPE_RELATIVE_HUMIDITY, UNIT_PERCENT) client.virtualWrite(23, n2_hdat, TYPE_RELATIVE_HUMIDITY, UNIT_PERCENT) client.virtualWrite(24, n2_latitude) client.virtualWrite(25, n2_longitude) client.virtualWrite(26, n2_pH) client.virtualWrite(29, n2_maybom) timestamp0 = time.time() if (time.time() > timestamp1 + 5): #LAY DU LIEU TU NODE 1
def on_message(message): global OnOff_Flag global MotorSaegeButton_Flag global KaltstartButton_Flag global WarmstartButton_Flag global BetriebButton_Flag global StartStopSignalButton_Flag global TestProfileButton_Flag global x1 global x2 global x3 global t1 global t2 global t3 if message.channel==1 : #channel for on/off button if message.value=="1": OnOff_Flag = True elif message.value=="0": OnOff_Flag = False elif message.channel==2 : #channel for MS if message.value=="1": MotorSaegeButton_Flag = True elif message.value=="0": MotorSaegeButton_Flag = False elif message.channel==4: #channel for cold start button if message.value=="1": KaltstartButton_Flag = True elif message.value=="0": KaltstartButton_Flag = False client.virtualWrite(18,0,"digital_sensor" , "d") elif message.channel==5: #channel for warm start button if message.value=="1": WarmstartButton_Flag = True elif message.value=="0": WarmstartButton_Flag = False client.virtualWrite(19,0,"digital_sensor" , "d") elif message.channel==6: #channel for betrieb button if message.value=="1": BetriebButton_Flag = True elif message.value=="0": BetriebButton_Flag = False client.virtualWrite(20,0,"digital_sensor" , "d") elif message.channel==7 : #channel for start/stop button if message.value=="1": StartStopSignalButton_Flag = True elif message.value=="0": StartStopSignalButton_Flag = False elif message.channel==8 : #channel for test profile button if message.value=="1": TestProfileButton_Flag = True elif message.value=="0": TestProfileButton_Flag = False elif message.channel==21: x1 = float(message.value) return x1 elif message.channel==22: x2 = float(message.value) return x2 elif message.channel==23: x3 = float(message.value) return x3 elif message.channel==24: t1 = float(message.value) return t1 elif message.channel==25: t2 = float(message.value) return t2 elif message.channel==26: t3 = float(message.value) return t3
data = 123 cs = 0 while True: try: rcv = port.readline() #read buffer until cr/lf #print("Serial Readline Data = " + rcv) rcv = rcv.rstrip("\r\n") node, channel, data, cs = rcv.split(",") #Test Point print("rcv.split Data = : " + node + channel + data + cs) if cs == '0': #if cs = Check Sum is good = 0 then do the following if channel == 'A': data = float(data) / 1 client.virtualWrite(1, data, "analog_sensor", "null") client.loop() if channel == 'B': data = float(data) / 1 client.virtualWrite(2, data, "analog_sensor", "null") client.loop() if channel == 'C': data = float(data) / 1 client.virtualWrite(3, data, "analog_sensor", "null") client.loop() if channel == 'D': data = float(data) / 1 client.virtualWrite(4, data, "analog_sensor", "null")
def on_message(message): global COUNTER print("message received: " + str(message)) client.virtualWrite(18, COUNTER, "analog", "null") COUNTER = COUNTER + 10
# Cayenne authentication info. This should be obtained from the Cayenne Dashboard. MQTT_USERNAME = "******" MQTT_PASSWORD = "******" MQTT_CLIENT_ID = "dd059960-54bb-11e9-83b2-37ef83221631" 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) #timestamp = 0 SCUTTLE_IDs = [248534172589, 623731415800, 919785904744] while True: client.loop() print("Hold a tag near the reader") id, text = reader.read() print("ID: %s\nText: %s" % (id, text)) n = 0 for x in SCUTTLE_IDs: if id == x: client.virtualWrite(n, 1, dataType="prox", dataUnit="d") else: client.virtualWrite(n, 0, dataType="prox", dataUnit="d") n = n + 1
# 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') client.mqttPublish(client.rootTopic + '/cmd/11', 'sendok,1') client.mqttPublish(client.rootTopic + '/cmd/12', 'done,1') start = time.time() while True: loop_start = time.time()
def main(): global n1pointer, n1temps, n2pointer, n2temps, n3pointer, n3temps, n4pointer, n4temps n1pointer = 0 n2pointer = 0 n3pointer = 0 n4pointer = 0 n1temps = [] n2temps = [] n3temps = [] n4temps = [] # garbage collection to reduce memory leaks added July 2, 2014 # gc is set to run every 21600 seconds (6 hours) #def foo(): # gc.collect() # threading.Timer(21600, foo).start() def runningAverage(node, temperature, pointer, temps): #print "RunningAverage function; pointer = %d" % pointer total = 0 # initially build-up the list of temperatures if len(temps) < 4: temps.extend([temperature]) for j in range(0, (pointer + 1)): addend = float(temps[j]) total = float(addend + total) avgx = total / (pointer + 1) # the list of temperatures is full, now replace the oldest one # with a new one else: temps[pointer] = temperature for j in range(0, 4): addend = float(temps[j]) total = float(addend + total) avgx = total / 4 average = round(avgx, 2) # increment or reset pointer if pointer < 3: pointer += 1 else: pointer = 0 return (node, average, pointer, temps) def calcTemp(): # routine to calculate single temperature units unkn = rawx.pop(0).strip() # don't know what this is, drop for now place = nodeList[int(node)] # substitute node for actual place in house wholeTemp = rawx.pop(0).strip() # whole number part of temperature fracTemp = rawx.pop(0).strip() # decimal part of temperature temperature = wholeTemp + "." + fracTemp return temperature # pass this on! nodeList = 'Office', 'Garage', 'MBL_Room', 'In-law_Suite', 'Pantry', 'Kitchen' # CPU monitor routine, requires "import os" def getCPUtemperature(): res = os.popen('vcgencmd measure_temp').readline() return(res.replace("temp=","").replace("'C\n","")) cpuTemp = int(float(getCPUtemperature())) # COSM variables. # f = open('apikey.txt', 'r') # API_KEY = f.read() # f.close() # API_KEY = 'suinLKP1uD3GCkuUN-xBmvZzSzWSAKxEcnQrdUJyTHJRND0g' # FEED = 129833 # API_URL = '/v2/feeds/{feednum}.xml' .format(feednum = FEED) ser = serial.Serial('/dev/ttyUSB0', 57600) # ser.close() while True: client.loop() x = ser.readline() OKtest = re.match ( 'OK', x ) # match tests for match at beginning of string, # otherwise use search if OKtest: #pac = eeml.datastream.Cosm(API_URL, API_KEY) #print "Raw data received: " + x rawx = x.split() # split on whitespace ###################### # initial parsing ack = rawx.pop(0).strip() # "OK": do nothing with it node = rawx.pop(0).strip() # Node number if node == '1': tempLow = rawx.pop(0).strip() # temperature low byte tempHigh = rawx.pop(0).strip() # temperature high byte if int(tempHigh) < 5: # if this byte is greater than 5, # temp is (for sure) a positive value tempRaw = (int(tempHigh) * 256) + int(tempLow) else: tempRaw = (255 ^ (int(tempLow))) * -1 # temp is negative value, so do a 1's complement tempRaw2 = tempRaw + 0.0 actualTemp = tempRaw2 / 10 humLow = rawx.pop(0).strip() # humidity low byte humHigh = rawx.pop(0).strip() # humidity high byte humRaw = (int(humHigh) * 256) + int(humLow) humRaw2 = humRaw + 0.0 actualHum = humRaw2 / 10 lightLow = rawx.pop(0).strip() # humidity low byte lightHigh = rawx.pop(0).strip() # humidity high byte lightRaw = (int(lightHigh) * 256) + int(lightLow) actualLight = lightRaw pir = rawx.pop(0).strip() # PIR sensor # Cayenne stuff: ******************************** #print("1: actualTemp: ", actualTemp) client.virtualWrite(1, actualTemp, "temp", "c") #print("2: actualHum: ", actualHum) client.virtualWrite(2, actualHum, "rel_hum", "p") #print("3: actualLight: ", actualLight) client.virtualWrite(3, actualLight, "lum", "p") #print("4: PIR: ", pir) client.virtualWrite(4, pir, "digital_sensor", "d") if node == '2': temperature = calcTemp() # Cayenne stuff: ******************************** client.virtualWrite(5, temperature, "temp", "c") # rolling average code: pointer = n2pointer temps = n2temps average = runningAverage(node, temperature, pointer, temps) node = average[0] avrg = average[1] pointer = average[2] temps = average[3] n2pointer = pointer n2temps = temps #print "Node: %s Avg Temp: %s Celcius Pointer: %s List: %s" % (node, avrg, pointer, temps) elif node == '3': temperature = calcTemp() # Cayenne stuff: ******************************** client.virtualWrite(6, temperature, "temp", "c") # rolling average code: pointer = n3pointer temps = n3temps average = runningAverage(node, temperature, pointer, temps) node = average[0] avrg = average[1] pointer = average[2] temps = average[3] n3pointer = pointer n3temps = temps #print "Node: %s Avg Temp: %s Celcius Pointer: %s List: %s" % (node, avrg, pointer, temps) elif node == '4': temperature = calcTemp() # Cayenne stuff: ******************************** client.virtualWrite(7, temperature, "temp", "c") # rolling average code: pointer = n4pointer temps = n4temps average = runningAverage(node, temperature, pointer, temps) node = average[0] avrg = average[1] pointer = average[2] temps = average[3] n4pointer = pointer n4temps = temps #print "Node: %s Avg Temp: %s Celcius Pointer: %s List: %s" % (node, avrg, pointer, temps) elif node == '5': tempLow = rawx.pop(0).strip() # temperature low byte tempHigh = rawx.pop(0).strip() # temperature high byte if int(tempHigh) < 5: # if this byte is greater than 5, # temp is (for sure) a positive value tempRaw = (int(tempHigh) * 256) + int(tempLow) else: tempRaw = (255 ^ (int(tempLow))) * -1 # temp is negative value, so do a 1's complement tempRaw2 = tempRaw + 0.0 actualTemp = tempRaw2 / 10 humLow = rawx.pop(0).strip() # humidity low byte humHigh = rawx.pop(0).strip() # humidity high byte humRaw = (int(humHigh) * 256) + int(humLow) humRaw2 = humRaw + 0.0 actualHum = humRaw2 / 10 bvLow = rawx.pop(0).strip() # batt volt low byte bvMid = rawx.pop(0).strip() # batt volt mid byte bvHigh = rawx.pop(0).strip() # batt volt high byte throwaway = rawx.pop(0).strip() # throw away this byte bvRaw = (int(bvHigh) * 65536) + (int(bvMid) * 256) + int(bvLow) actualBv = bvRaw * 3.3 / 512 # 512 or 1024, whichever works! Bv = round(actualBv, 2) spvLow = rawx.pop(0).strip() # solarpanel low byte spvMid = rawx.pop(0).strip() # solarpanel mid byte spvHigh = rawx.pop(0).strip() # solarpanel high byte throwaway = rawx.pop(0).strip() # throw away this byte spvRaw = (int(spvHigh) * 65536) + (int(spvMid) * 256) + int(spvLow) actualspv = spvRaw * 3.3 /512 # 512 or 1024, whichever works! Spv = round(actualspv, 2) # Cayenne stuff: ******************************** client.virtualWrite(8, actualTemp, "temp", "c") client.virtualWrite(9, actualHum, "rel_hum", "p") client.virtualWrite(10, Bv, "voltage", "v") client.virtualWrite(11, Spv, "voltage", "v") elif node == '6': # Oil Tank Level Sender oilLevel = rawx.pop(0).strip() client.virtualWrite(12, oilLevel, "tl", "gauge") elif node == '10': # Garage Node 10 tempLow = rawx.pop(0).strip() # temperature low byte tempHigh = rawx.pop(0).strip() # temperature high byte if int(tempHigh) < 5: # if this byte is greater than 5, # temp is (for sure) a positive value tempRaw = (int(tempHigh) * 256) + int(tempLow) else: tempRaw = (255 ^ (int(tempLow))) * -1 # temp is negative value, so do a 1's complement tempRaw2 = tempRaw + 0.0 actualTemp = tempRaw2 / 10 # Garage Temperature *************** humLow = rawx.pop(0).strip() # humidity low byte humHigh = rawx.pop(0).strip() # humidity high byte humRaw = (int(humHigh) * 256) + int(humLow) humRaw2 = humRaw + 0.0 actualHum = humRaw2 / 10 # Garage Humidity ****************** tempLow = rawx.pop(0).strip() # temperature low byte tempHigh = rawx.pop(0).strip() # temperature high byte if int(tempHigh) < 5: # if this byte is greater than 5, # temp is (for sure) a positive value tempRaw = (int(tempHigh) * 256) + int(tempLow) else: tempRaw = (255 ^ (int(tempLow))) * -1 # temp is negative value, so do a 1's complement tempRaw2 = tempRaw + 0.0 actualTempWB = tempRaw2 / 10 # Wormbox Temperature ************** humLow = rawx.pop(0).strip() # humidity low byte humHigh = rawx.pop(0).strip() # humidity high byte humRaw = (int(humHigh) * 256) + int(humLow) humRaw2 = humRaw + 0.0 actualHumWB = humRaw2 / 10 # Wormbox Humidity ***************** coLow = rawx.pop(0).strip() # Carbon Monoxide high byte coHigh = rawx.pop(0).strip() # Carbon Monoxide low byte coRaw = (int(coHigh) * 256) + int(coLow) actualco = coRaw #actualco = coRaw2 / 10 # CO Level ************************* # Garage Door Sensor Reading for Test gdLow = rawx.pop(0).strip() # garage door low byte FOR TEST gdHigh = rawx.pop(0).strip() # garage door high byte #gdRaw = (int(gdHigh) * 256) + int(gdLow) garageDoor = rawx.pop(0).strip() # garage door client.virtualWrite(13, actualTemp, "temp", "c") client.virtualWrite(14, actualHum, "rel_hum", "p") client.virtualWrite(15, actualco, "co", "value") client.virtualWrite(16, garageDoor, "digital_sensor", "d") #print "Node: %s CO2High: %s CO2Low: %s Garage Door: %s LDRHigh: %s LDRLow: %s" % (node, co2High, co2Low, garageDoor, ldrHigh, ldrLow) if node == '11': tempLow = rawx.pop(0).strip() # temperature low byte tempHigh = rawx.pop(0).strip() # temperature high byte if int(tempHigh) < 5: # if this byte is greater than 5, # temp is (for sure) a positive value tempRaw = (int(tempHigh) * 256) + int(tempLow) else: tempRaw = (255 ^ (int(tempLow))) * -1 # temp is negative value, so do a 1's complement tempRaw2 = tempRaw + 0.0 actualTemp = tempRaw2 / 10 humLow = rawx.pop(0).strip() # humidity low byte humHigh = rawx.pop(0).strip() # humidity high byte humRaw = (int(humHigh) * 256) + int(humLow) humRaw2 = humRaw + 0.0 actualHum = humRaw2 / 10 bvLow = rawx.pop(0).strip() # batt volt low byte bvMid = rawx.pop(0).strip() # batt volt mid byte bvHigh = rawx.pop(0).strip() # batt volt high byte throwaway = rawx.pop(0).strip() # throw away this byte bvRaw = (int(bvHigh) * 65536) + (int(bvMid) * 256) + int(bvLow) actualBv = bvRaw * 3.3 / 1024 Bv = round(actualBv, 2) spvLow = rawx.pop(0).strip() # solarpanel low byte spvMid = rawx.pop(0).strip() # solarpanel mid byte spvHigh = rawx.pop(0).strip() # solarpanel high byte throwaway = rawx.pop(0).strip() # throw away this byte spvRaw = (int(spvHigh) * 65536) + (int(spvMid) * 256) + int(spvLow) actualspv = spvRaw * 3.3 /1024 Spv = round(actualspv, 2) client.virtualWrite(17, actualTemp, "temp", "c") client.virtualWrite(18, actualHum, "rel_hum", "p") client.virtualWrite(19, Bv, "voltage", "v") client.virtualWrite(20, Spv, "voltage", "v")
#!/usr/bin/env python import cayenne.client import time # Cayenne authentication info. This should be obtained from the Cayenne Dashboard. MQTT_USERNAME = "******" MQTT_PASSWORD = "******" MQTT_CLIENT_ID = "49ba49c0-8a8c-11e8-9c05-61f9e9bc1eea" # 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) # For a secure connection use port 8883 when calling client.begin: # client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID, port=8883) a = 55 b = 99 timestamp = 0 while True: client.loop() if (time.time() > timestamp + 10): client.virtualWrite(1, a) client.virtualWrite(20, b) timestamp = time.time()
def cayene(valors): persones = valors client.virtualWrite(1, persones, "Comptador", "Persones")
parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=1) print("Inici lectura!") client = cayenne.client.CayenneMQTTClient() #client.on_message = on_message client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID) while True: try: data = str(arduino.readline()) d = data[2:-1] c = d.split(";") #print(len(c)) if (len(c) > 1): print(c) client.loop() client.virtualWrite(0, c[0]) client.virtualWrite(1, c[1]) client.virtualWrite(2, c[2]) #except KeyboardInterrupt: #break except: pass arduino.close() sys.exit()
Connection_Counter = 0 Counter = 0 # Zeit Motor_Timer = time() Connection_Timer = 0 x = 0 MQTT_USERNAME = "******" MQTT_PASSWORD = "******" MQTT_CLIENT_ID = "346f3e40-8341-11ea-a67f-15e30d90bbf4" client = cayenne.client.CayenneMQTTClient() client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID) client.virtualWrite(8,0) def on_message(message): global OnOff_Flag global MotorSaegeButton_Flag global KaltstartButton_Flag global WarmstartButton_Flag global BetriebButton_Flag global StartStopSignalButton_Flag global TestProfileButton_Flag global x1 global x2 global x3 global t1 global t2 global t3
LOCATION_KEY = "2094707" API_URL = "https://dataservice.accuweather.com/currentconditions/v1/" params = {'apikey': API_KEY, 'details': True} ser.isOpen() out = b'' moist = 0 prev_time = datetime.datetime.now() - datetime.timedelta(hours=1.1) start_time = datetime.datetime.now() while True: now_time = datetime.datetime.now() uptime = now_time - start_time client.loop() client.virtualWrite(0, uptime.total_seconds(), "counter", "null") while ser.inWaiting() > 0: out += ser.read(1) if out != b'': b_val = out.strip() try: moist = float(b_val) out = b'' if moist < 0 or moist > 100: raise Exception() if now_time >= (prev_time + datetime.timedelta(hours=1)): print(str(datetime.datetime.now()) + ": Polling weather data") response = requests.get(API_URL + LOCATION_KEY, params=params) weather_data = response.json() cur_temp = weather_data[0]['Temperature']['Imperial'][ 'Value'] #F
print("Topic=" + str(message.topic)) print("Channel=" + str(message.channel)) print("Value=" + str(message.value)) # 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) # For a secure connection use port 8883 when calling client.begin: # client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID, port=8883) i = 0 timestamp = 0 while True: client.loop() line = ser.readline() t = line[7:11] h = line[25:30] #print (line) #print (t) #print (h) if (time.time() > timestamp + 2): client.virtualWrite(0, t) client.virtualWrite(1, h) timestamp = time.time() i = i + 1
def cayene(valors): temperatura = valors[0] humitat = valors[1] client.virtualWrite(1, temperatura, "temp", "C") client.virtualWrite(2, humitat)
def on_message(message): global OnOff_Flag global MotorSaegeButton_Flag global FreischneideButton_Flag global TrennschleiferButton_Flag global KaltstartButton_Flag global WarmstartButton_Flag global BetriebButton_Flag global StartStopSignalButton_Flag global TestProfileButton_Flag global Time_1 global Time_2 global Time_3 global Throttle_1 global Throttle_2 global Throttle_3 global Throttle if message.channel == 1: #channel for on/off button if message.value == "1": OnOff_Flag = True elif message.value == "0": OnOff_Flag = False elif message.channel == 2: #channel for MS if message.value == "1": MotorSaegeButton_Flag = True elif message.value == "0": MotorSaegeButton_Flag = False elif message.channel == 3: #channel for FS if message.value == "1": FreischneideButton_Flag = True elif message.value == "0": FreischneideButton_Flag = False elif message.channel == 4: #channel for TS if message.value == "1": TrennschleiferButton_Flag = True elif message.value == "0": TrennschleiferButton_Flag = False elif message.channel == 5: #channel for cold start button if message.value == "1": KaltstartButton_Flag = True elif message.value == "0": KaltstartButton_Flag = False client.virtualWrite(18, 0, "digital_sensor", "d") elif message.channel == 6: #channel for warm start button if message.value == "1": WarmstartButton_Flag = True elif message.value == "0": WarmstartButton_Flag = False client.virtualWrite(19, 0, "digital_sensor", "d") elif message.channel == 7: #channel for betrieb button if message.value == "1": BetriebButton_Flag = True elif message.value == "0": BetriebButton_Flag = False client.virtualWrite(20, 0, "digital_sensor", "d") elif message.channel == 8: #channel for start/stop engine button if message.value == "1": StartStopSignalButton_Flag = True elif message.value == "0": StartStopSignalButton_Flag = False elif message.channel == 9: #channel for on/off test profile button if message.value == "1": TestProfileButton_Flag = True elif message.value == "0": TestProfileButton_Flag = False elif message.channel == 11: #channel for throttle 1 slider Throttle_1 = float(message.value) elif message.channel == 12: #channel for throttle 2 slider Throttle_2 = float(message.value) elif message.channel == 13: #channel for throttle 3 slider Throttle_3 = float(message.value) elif message.channel == 14: #channel for time 1 slider Time_1 = float(message.value) elif message.channel == 15: #channel for time 2 slider Time_2 = float(message.value) elif message.channel == 16: #channel for time 3 slider Time_3 = float(message.value) elif message.channel == 17: #channel for throttle Throttle = float(message.value)
def produceData(): global current global client global light # email configuration sender_email = "Your Fridge <*****@*****.**>" receiver_email = "*****@*****.**" # threshold temp in C EMAIL_FRIDGE_THRESH = 7 EMAIL_FREEZER_THRESH = -10 # time in seconds that threshold must be exceeded EMAIL_THRESHOLD_TIME = 1200 # min alert email interval in seconds EMAIL_ALERT_INTERVAL = 86400 # informative message template text = """\ From: {} To: {} Subject: HIGH TEMPERATURE ALERT Hi, On {}, the fridge was {} deg C and the freezer was {} deg C. Click http://10.0.0.8:8080/view?scale=day for more information. """ """ thread to aquire samples continuously """ #file = open("/var/1w_files/log.csv", "a") # bootstrap timers (take/send readings immediately on start) timestamp = time.time() - 5 cayenne_timestamp = time.time() - 280 # create sensor/control objects, GPIO and 1wire light = gpio_sensor.Gpio("gpio27") switch = gpio_sensor.Gpio("gpio22") ambient = temp_sensor.TempSensor("28-0000052f7386") freezer = temp_sensor.TempSensor("28-0000055fc26e") fridge = temp_sensor.TempSensor("28-0000052f91b1") # timers for alarm threshold & alert rate limiting threshold_timestamp = time.time() last_alert_timestamp = 0 # send alert immediately after threshold time while(True): if (time.time()-timestamp) > 5.0 : timestamp = time.time() # grab temperature data. skip sensor in case of error try: ambient_temp = ambient.get_temperature() except Exception: pass try: freezer_temp = freezer.get_temperature() except Exception: pass try: # fridge thermometer has offset #fridge_temp = fridge.get_temperature() - 3.333 # fridge temp offset dhanged 12/25/2019 fridge_temp = fridge.get_temperature() + 2.000 except Exception: pass light_state = light.get_value() switch_state = switch.get_value() # light control logic FDefrost = freezer_temp >= -6.0 # defrost mode in freezer FHigh = (freezer_temp < -6.0) & (freezer_temp > -15.0) # "high" FLow = freezer_temp <= -15.0 # freezer temp is "low" RHigh = fridge_temp > 8.0 # fridge temp is "high" RBand = (fridge_temp <= 8.0) & (fridge_temp >= 1.5) # "band" RLow = fridge_temp < 1.5 # fridge temp is "low" Door = switch_state == 1 control = (FHigh & RBand) | RLow | Door light_state = to_int(control) light.put_value(light_state) current = { "time": timestamp, "ambient": ambient_temp, "freezer": freezer_temp, "fridge": fridge_temp, "light": light_state, "switch": switch_state, } print("Producer: "), print(current) #update rrdtool database. rrdtool is used for webpage graphics rrdtool.update("/var/1w_files/templog.rrd", \ "%d:%s:%s:%s:%s:%s" % (timestamp, \ ambient_temp, \ freezer_temp, \ fridge_temp, \ light_state, \ switch_state)) # update element in queue for socketserver try: q.get(False) # empty the old queue element except Exception: pass # queue was empty already q.put(current, False) # insert new element # log all data to file #foo = ("%d,%s,%s,%s,%s\n") % ( current["time"], current["freezer"], current["fridge"], current["ambient"], current["light"] ) #file.write(foo) #file.flush() # update cayenne about every 5 minutes if ((time.time() - cayenne_timestamp) > 300): print("Publish to cayenne") cayenne_timestamp = time.time() client.celsiusWrite(1, ambient_temp) client.celsiusWrite(2, freezer_temp) client.celsiusWrite(3, fridge_temp) client.virtualWrite(4, light_state, dataType="digital_actuator", dataUnit="d") client.loop() # check for alarm condition and possibly send email if ( (freezer_temp < EMAIL_FREEZER_THRESH) and (fridge_temp < EMAIL_FRIDGE_THRESH) ): # everything normal, reset threshold exceeded time to current time threshold_timestamp = time.time() else: # we have a problem, maybe send email if (( (time.time() - threshold_timestamp) > EMAIL_THRESHOLD_TIME) and (( time.time() - last_alert_timestamp) > EMAIL_ALERT_INTERVAL) ): # send email, threshold exceeded and alert interval exceeded print("Send alert email now!"); proc = Popen(['/usr/sbin/sendmail','-t','-oi'], stdin=PIPE) print(text.format(sender_email,receiver_email,time.strftime("%c"),fridge_temp,(fridge_temp*C_TO_F+32),freezer_temp,(freezer_temp*C_TO_F+32)).encode('utf8')) proc.communicate(text.format(sender_email,receiver_email,time.strftime("%c"),fridge_temp,freezer_temp).encode('utf8')) proc.wait() # we sent an alert, so reset rate-limiting timer last_alert_timestamp = time.time() # end of while(True) else: # check for cayenne publish or commands client.loop() time.sleep(0.1)
#!/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)