Пример #1
0
def senddata():
    ds.convert_temp()
    time.sleep_ms(100)
    temp = ds.read_temp(roms[0])
    print("Temperature: %f" % temp)
    client.celsiusWrite(ds18b20Channel, temp)
    time.sleep(5)
Пример #2
0
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)
Пример #3
0
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()
Пример #4
0
def senddata():
    sht30Temperature, sht30Humidity = sht30.measure()
    print("Temperature: %6.3f" % sht30Temperature)
    client.celsiusWrite(sht30TempChannel, sht30Temperature)
    time.sleep(5)
    print("Relative humidity: %6.3f" % sht30Humidity + '%')
    client.humidityWrite(sht30HumidityChannel, sht30Humidity)
    time.sleep(5)
Пример #5
0
def senddata():
  sht30Temperature, sht30Humidity = sht30.getTempAndHumi(clockStretching=SHT3X.NO_CLOCK_STRETCH,repeatability=SHT3X.REP_S_HIGH)
  print("Temperature: %6.3f"%sht30Temperature)
  client.celsiusWrite(sht30TempChannel,sht30Temperature)
  client.celsiusWrite(sht30TempChannel+1,sht30Temperature)
  print("Relative humidity: %6.3f"%sht30Humidity + '%')
  client.humidityWrite(sht30HumidityChannel,sht30Humidity)
  client.humidityWrite(sht30HumidityChannel+1,sht30Humidity)  
Пример #6
0
def senddata():
    bmp180.blocking_read()
    temp = bmp180.temperature
    p = bmp180.pressure
    altitude = bmp180.altitude
    print(temp, p, altitude)
    client.celsiusWrite(bmp180TempChannel, temp)
    time.sleep(1)
    client.hectoPascalWrite(bmp180PressChannel, p / 100.0)
    time.sleep(4)
Пример #7
0
def senddata():
    print("Measuring...")
    dht11.measure()
    temp = dht11.temperature()
    print("Temperature: %f °C" % temp)
    client.celsiusWrite(dht11TempChannel, temp)
    time.sleep(5)
    humidity = dht11.humidity()
    print("Relative humidity: %6.3f" % humidity + '%')
    client.humidityWrite(dht11HumidityChannel, humidity)
    time.sleep(5)
Пример #8
0
def dht():
    print("\nInitializing DHT sensor...\n")
    time.sleep(2)
    while True:
        client.loop()
        
        humidity, temperature=Adafruit_DHT.read_retry(11,17)
        if humidity is not None and temperature is not None:
            client.celsiusWrite(1, temperature)
            client.luxWrite(2, humidity)
            print('Temp:{0:0.1f}*C Humidity: {1:0.1f}%'.format(temperature,humidity))
            time.sleep(2)
        else:
            print("\nFailed to get reading...\n")
Пример #9
0
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()
Пример #10
0
address = 0x76
bus = smbus2.SMBus(port)

bme280.load_calibration_params(bus, address)

# the sample method will take a single reading and return a
# compensated_reading object
data = bme280.sample(bus, address)

# the compensated_reading class has the following attributes
#print(data.id)
#print(data.timestamp)
#print(data.temperature)
#print(data.pressure)
#print(data.humidity)
vacuum = abs((data.pressure * 0.02953) - 29.53)
#print(vacuum)
temp = data.temperature

while True:
    client.loop()

    if (time.time() > timestamp + 10):
        data = bme280.sample(bus, address)
        vacuum = abs((data.pressure * 0.02953) - 29.53)
        temp = data.temperature
        client.celsiusWrite(1, temp)
        client.humidityWrite(2, data.humidity)
        client.vacuumWrite(3, vacuum)
        timestamp = time.time()
Пример #11
0
            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()
        client.loop()
Пример #12
0
    rcv = rcv.decode("utf-8")  #buffer read is 'bytes' in Python 3.x
    #this makes it 'str'
    rcv = rcv.rstrip("\r\n")
    #			node,channel,data,chksum = rcv.split(",")
    print("Read: >" + rcv + "<", rcv.count(','))
    #			print("Read: >",rcv,node,channel,data,chksum,"<")
    #			if chksum == '0':	# Checksum check should be added here
    if rcv.count(',') > 1:
        # 				Channel = alpha, data2 = 0-255, checksum,
        node, channel, data, chksum = rcv.split(",")
        #				print("rcv: " + node + channel + data )
        details = sensor_nodes.get(node)
        if channel == 'A':
            data = float(data) / 10
            print(data)
            client.celsiusWrite(1, data)
            client.loop()
#				elif channel == 'B':
#			print 'Current', details[sensor_fullname], 'is', str(data)+details[sensor_unit]
#					print( 'Writing to Sheet:',time.ctime(time.time()) )
#					rowOfData = [time.strftime("%Y-%m-%d_%H:%M:%S"),node,channel,data]
#					sheet.append_row(rowOfData)
#					print( 'Waiting:',time.ctime(time.time()) )
#					while (time.time() < timedata + interval):
#						time.sleep(1)
#
#			timedata = time.time()
#    			print(timestamp)
#		except ValueError:
#       	         print("opps..."+"rcv: " + channel + node + data)
Пример #13
0
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)
# 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()
    #if (time.time() > timestamp):
    humidity, temperature = Adafruit_DHT.read_retry(11, 4)
    #print 'Temp: {0:0.1f} C  Humidity: {1:0.1f} %'.format(temperature, humidity)
    time.sleep(1)
    client.celsiusWrite(1, temperature)
    client.celsiusWrite(3, humidity)
    #client.percentWrite(2, i*10)
    #client.hectoPascalWrite(3, i+800)
    #timestamp = time.time()
    #i = i+1
Пример #14
0
def senddata():
    dummyTemperature = 25.0 + 10 * random(
    )  # add a random value between 0 and 10
    print("Temperature: %6.3f" % dummyTemperature)
    client.celsiusWrite(dummyTempChannel, dummyTemperature)
    time.sleep(2)
Пример #15
0
    # 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)

i = 0
timestamp = 0

while True:
    client.loop()

    if (time.time() > timestamp + 30):
        a = random.uniform(1.234, 9.876)
        client.celsiusWrite(1, a)
        time.sleep(3)

        b = random.randrange(33, 77)
        client.luxWrite(2, b)
        time.sleep(3)

        c = random.randrange(0, 100, 5)
        client.hectoPascalWrite(3, c)
        time.sleep(3)

        k = random.randint(7, 93)
        client.luxWrite(4, k)

        timestamp = time.time()
Пример #16
0
    # 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):
        # 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()
Пример #17
0
import cayenne.client
import time

# Cayenne authentication info. This should be obtained from the Cayenne Dashboard.
MQTT_USERNAME = "******"
MQTT_PASSWORD = "******"
MQTT_CLIENT_ID = "741b6b30-7962-11e8-861b-e79eceb83d4e"

client = cayenne.client.CayenneMQTTClient()
client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID)

# Sensor should be set to Adafruit_DHT.DHT11,
# Adafruit_DHT.DHT22, or Adafruit_DHT.AM2302.
sensor = Adafruit_DHT.DHT11

# Example using a Raspberry Pi with DHT sensor
# connected to GPIO23.
pin = 14

while True:
    client.loop()

    humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
    if humidity is not None and temperature is not None:
        print('Temp={0:0.1f}*C  Humidity={1:0.1f}%'.format(
            temperature, humidity))
        client.celsiusWrite(1, temperature)
        client.luxWrite(2, humidity)
    else:
        print('Failed to get reading. Try again!')
Пример #18
0
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)
             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)


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


while True:
    client.loop()
    if (time.time() > timestamp + 10):
        sensor_value = i
        client.celsiusWrite(DATA_CHANNEL, sensor_value)
        send_trigger_value(TRIGGER_CHANNEL, sensor_value, THRESHOLD,
                           send_below_threshold)
        timestamp = time.time()
        i = i + 1
        if (i == 12
            ):  # Reset the sensor value to test that the trigger gets reset.
            i = 0
Пример #20
0
MQTT_CLIENT_ID = "xxx"

# llegir la data llegint el pin 11
instance = dht11.DHT11(pin=11)
result = instance.read()


def on_message(message):
    print("missatge rebut: " + str(message))


#connexió
client = cayenne.client.CayenneMQTTClient()
client.on_message = on_message
client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID, port=8883)

while True:
    try:
        client.loop()
        #print("temperatura: "+str(result.temperature))
        client.celsiusWrite(0, result.temperature)
        #print("humitat: "+str(result.humidity))
        client.virtualWrite(1, result.humidity)
        timestamp = time.time()
        time.sleep(60)

    except KeyboardInterrupt:
        break

sys.exit()
Пример #21
0
            node = "node2getdata"
        print(node + " SENT@")
        ser.write(node)
        n_line = ser.readline()
        n_line = n_line.strip()
        n_line1 = n_line.split('|')
        print(n_line)
        print(n_line1)
        timestamp = time.time()

    if (time.time() > clientstamp + 10):
        #node_c = n_line[0:5]
        if (n_line1[0] == "Node1"):

            #IN DU LIEU LEN WEBSERVER CAYENNE NODE 1
            client.celsiusWrite(11, n_line1[1])
            client.virtualWrite(12, n_line1[2], TYPE_RELATIVE_HUMIDITY,
                                UNIT_PERCENT)
            client.virtualWrite(13, n_line1[3], TYPE_RELATIVE_HUMIDITY,
                                UNIT_PERCENT)
            client.virtualWrite(14, n_line1[4])
            client.virtualWrite(15, n_line1[5])
            client.virtualWrite(17, n_line1[6])
        elif (n_line1[0] == "Node2"):

            #IN DU LIEU LEN WEBSERVER CAYENNE NODE 2
            client.celsiusWrite(21, n_line1[1])
            client.virtualWrite(22, n_line1[2], TYPE_RELATIVE_HUMIDITY,
                                UNIT_PERCENT)
            client.virtualWrite(23, n_line1[3])
            client.virtualWrite(24, n_line1[4])
Пример #22
0
n1_latitude = 0
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):
Пример #23
0
    #Change the pin back to input
    GPIO.setup(ldr, GPIO.IN)

    #Count until the pin goes high
    while (GPIO.input(ldr) == 0):
        count += 1

    return count


while True:
    client.loop()

    lux = rc_time(ldr)
    print(lux)
    if (lux > 7000):
        lamp_out = 1

    if (lux <= 7000):
        lamp_out = 0

    if (time.time() > timestamp + 10):
        client.celsiusWrite(1, temp_in)
        client.luxWrite(2, lux)
        client.celsiusWrite(3, temp_out)
        client.umidWrite(5, 67)
        client.digitalWrite(6, movimento)
        client.digitalWrite(7, porta)
        client.tankWrite(8, tankL)
        client.digitalWrite(10, lamp_out)
        timestamp = time.time()
Пример #24
0
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)
Пример #25
0
import time

# Cayenne authentication info. This should be obtained from the Cayenne Dashboard.
MQTT_USERNAME = "******"
MQTT_PASSWORD = "******"
MQTT_CLIENT_ID = "377428e0-526a-11e7-aaa7-cf0a7ad22796"


# 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)

i = 0
timestamp = 0

while True:
    client.loop()

    if (time.time() > timestamp + 30):
        client.celsiusWrite(1, i + 10)
        client.luxWrite(2, i * 10 + 20)
        client.hectoPascalWrite(3, i + 900)
        timestamp = time.time()
        i = i + 2
import cayenne.client
import time

# 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)

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
Пример #27
0
                        parity='N',
                        stopbits=1,
                        timeout=1)
except serial.serialutil.SerialException:
    print('Wrong serial port number, try again.')
    sys.exit()

        
while True:
    client.loop()
    
    line = ser.readline()# read a '\n' terminated line
    if(line!=b''):
        if line.startswith(b'src '):
            mesh_node_id = int(str(line[4:10], encoding="utf-8"), 16)
            mesh_dict[mesh_node_id] = time.time()
            #print(mesh_node_id)


        
    if (time.time() > timestamp + 5):
        for mesh_node_id in mesh_dict.keys():
            #print(mesh_node_id)
            if(time.time() > mesh_dict[mesh_node_id] + 10):
                client.celsiusWrite(mesh_node_id, 0)
            else:
                client.celsiusWrite(mesh_node_id, 1)

        timestamp = time.time()
    
Пример #28
0

client = cayenne.client.CayenneMQTTClient()
client.on_message = on_message
client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID)

i = 0
timestamp = 0
channels = {
    'temperature': 1,
    'humidity': 2,
}
PERIOD_S = 10


class SensorMock(object):
    def read_temperature_and_humidity(self):
        return 12, 23


while True:
    client.loop()

    time.sleep(PERIOD_S)
    #sensor = Hts221()
    sensor = SensorMock()
    temperature, humidity = sensor.read_temperature_and_humidity()
    client.celsiusWrite(channels['temperature'], temperature)
    client.virtualWrite(channels['humidity'], humidity, TYPE_RELATIVE_HUMIDITY,
                        UNIT_PERCENT)
Пример #29
0
def on_message(message):
    print("message received: " + str(message))
    # If there is an error processing the message return an error string, otherwise return nothing.


cgminer = CgminerAPI(host=os.getenv('CGMINER_HOST'),
                     port=int(os.getenv('CGMINER_PORT')))

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)

timestamp = 0

while True:
    client.loop()

    if (time.time() > timestamp + 5):
        STATS = cgminer.estats()['STATS'][0]
        client.celsiusWrite(1, int(STATS["temp1"]))
        client.celsiusWrite(2, int(STATS["temp2"]))

        client.virtualWrite(3, float(STATS['voltage']),
                            cayenne.client.TYPE_VOLTAGE,
                            cayenne.client.UNIT_VOLTS)
        client.virtualWrite(4, float(STATS["GHS 5s"]),
                            cayenne.client.TYPE_VOLTAGE, 'GHs')
        timestamp = time.time()
Пример #30
0
#!/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
# copyright U. Raich
# This is a demo program for the workshop  on IoT at the African Internet Summit 2019
# Released under GPL
#

import cayenne.client
import time
import logging
import random

# Cayenne authentication info. This should be obtained from the Cayenne Dashboard.
MQTT_USERNAME = "******"
MQTT_PASSWORD = "******"
MQTT_CLIENT_ID = "CAYENNE_CLIENT_ID"

tempChannel = 0

client = cayenne.client.CayenneMQTTClient()
client.begin(MQTT_USERNAME,
             MQTT_PASSWORD,
             MQTT_CLIENT_ID,
             loglevel=logging.INFO)
random.seed(5)

while True:
    client.loop()
    temp = 28.0 + random.getrandbits(8) / 50.
    print("Sending a temperature value of %f degrees C" % temp)
    client.celsiusWrite(tempChannel, temp)
    time.sleep(5)