예제 #1
0
 def Fkondenz(self, _isTest):
     self.isTest = _isTest
     self.dweet = Dweet()
     try:
         self.ser = serial.Serial('/dev/ttyUSB0', 9600)
     except NameError:
         pass
예제 #2
0
    def __init__(self, _isTest):
        self.testData = None
        self.testData1 = None
        self.testData2 = None

        self.isTest = _isTest
        self.dweet = Dweet()
        try:
            self.ser = serial.Serial('/dev/ttyUSB0', 9600)
        except NameError:
            pass
예제 #3
0
파일: Switch.py 프로젝트: heildever/iot
 def final(self, bright):
     self.payload = {
         "timestamp": self.timestamp,
         "mode": bright,
         "DeviceID": self.id
     }
     publish.single("switch/" + self.id,
                    json.dumps(self.payload),
                    hostname=self.brokerIP)
     name = self.id.replace("/", "")
     name = name + "S"
     Dweet.dweet_by_name(name="{}".format(name), data=self.payload)
     return """ The selected node will run on MANU mode with brightness : %s """ % bright + self.index(
     )
예제 #4
0
def callback():
    t1 = 18. + 10. * random.random()
    t2 = 18. + 10. * random.random()
    h1 = 65. + 25. * random.random()
    h2 = 65. + 25. * random.random()

    t1Buffer.push(t1)
    t2Buffer.push(t2)
    h1Buffer.push(h1)
    h2Buffer.push(h2)

    t1min, t1max = t1Buffer.get_min_max()
    t2min, t2max = t2Buffer.get_min_max()
    h1min, h1max = h1Buffer.get_min_max()
    h2min, h2max = h2Buffer.get_min_max()

    data = {
        'bac1':
        {
            'temperature':
            {
                'current':  t1,
                'min':      t1min,
                'max':      t1max,
            },
            'humidity':
            {
                'current':  h1,
                'min':      h1min,
                'max':      h1max,
            },
        },
        'bac2':
        {
            'temperature':
            {
                'current':  t2,
                'min':      t2min,
                'max':      t2max,
            },
            'humidity':
            {
                'current':  h2,
                'min':      h2min,
                'max':      h2max,
            },
        }
    }
    dweet = Dweet()
    dweet.post(data)
예제 #5
0
 def publish_data(self, data):
     logger.debug("Sub: Publishing the data to upstream!")
     dweet = Dweet.get_instance()
     if dweet:
         dweet.dweet(data)
     cloud = Cloud.get_instance()
     if cloud:
         cloud.send_to_cloud(data)
예제 #6
0
파일: Switch.py 프로젝트: heildever/iot
 def modeselect(self, zone, node, mode):
     if "zone" + zone not in self.actives:
         return "The selected node does not exist, please select a new one" + self.index(
         )
     self.id = "zone" + zone + "/" + "node" + node
     if int(mode) == 1:  # auto mode
         self.payload = {
             "timestamp": self.timestamp,
             "mode": '5',
             "DeviceID": self.id
         }
         publish.single("switch/" + self.id,
                        json.dumps(self.payload),
                        hostname=self.brokerIP)
         name = self.id.replace("/", "")
         name = self.id + "S"
         Dweet.dweet_by_name(name="{}".format(name), data=self.payload)
         return """ The selected node will be run on AUTO mode""" + self.index(
         )
     else:  # manu mode
         return """
예제 #7
0
class View(object):
    __dweet = Dweet()

    def __init__(self, database):
        self.__database = database

    def insertDataIntoDatabase(self, hum, temp):
        """
        Inserts the data into the database
        :param hum:
        :param temp:
        :return:
        """
        self.__database.insertDataBySensorID(StaticData.DHT_HUM_ID, hum)
        self.__database.insertDataBySensorID(StaticData.DHT_TEMP_ID, temp)

    def sendData(self, hum, temp, dist):
        """
        Sends the sensor data to dweet.io and returns 'success' on success and 'failed' on failure
        :param hum:
        :param temp:
        :param dist:
        :return:
        """
        try:
            resp = View.__dweet.dweet_by_name(name=StaticData.DWEET_ID, data={Sensor.STR_HUMIDITY: hum,
                                                                              Sensor.STR_TEMPERATURE: temp,
                                                                              Sensor.STR_DISTANCE: dist}
                                              )
            return resp['this']
        except requests.exceptions.ConnectionError:
            return "Connection error"

    def uploadToDweet(self, hum, temp, dist):
        """
        Test method wichi will print the data, send it to dweet.io and print the result
        :param hum:
        :param temp:
        :param dist:
        :return:
        """
        print "Sending"
        print "\tHumidity: ", hum
        print "\tTemperature: ", temp
        print "\tDistance: ", dist

        resp = self.sendData(hum, temp, dist)
        print "Result: " + resp + '\n'
예제 #8
0
    def test_e2e_readSensors_sendToDweet(self):
        fkond = Fkondenz(True)
        dweet = Dweet()

        testData = 1
        testData1 = 2
        testData2 = 3

        fkond.setTestData(testData)
        fkond.setTestData(testData1)
        fkond.setTestData(testData2)

        testData_, testData1_, testData2_ = fkond.readSensors()

        fkond.uploadToDweet(testData_, testData1_, testData2_)

        self.assertEqual(fkond.getTestData(), "Uploaded")
예제 #9
0
pins = (
    (GPIO_CS, 'out'),
    (BUTTON, 'in'),
    (RELE, 'out'),
    (LED, 'out'),
)

spi = spidev.SpiDev()
spi.open(0, 0)
spi.max_speed_hz = 10000
spi.mode = 0b00
spi.bits_per_word = 8

system_status = 1

dweet = Dweet()


def readDigital(gpio):
    digital = [0, 0]
    digital[0] = gpio.digital_read(LED)
    digital[1] = gpio.digital_read(RELE)

    return digital


def writeDigital(gpio, digital):
    write = digital
    gpio.digital_write(LED, write[0])
    gpio.digital_write(RELE, write[1])
예제 #10
0
 if __name__ == "__main__":
    devicename='bits279'#default device name
    if len(sys.argv)>1:#checking for any command line args
        devicename=sys.argv[1]#if found then change the device name to the first command line argument
    prev=datetime.strptime("00:00:00","%H:%M:%S");# initialise the timestamp of the previous command to 0
    test=serial.Serial("/dev/ttyAMA0",9600)#initialise serial port at 9600 baudrate
   
    #initialise the GPIO Pins 
    GPIO.setmode(GPIO.BOARD)#use the board pin numberings
    GPIO.setup(7,GPIO.OUT)#set 7,11,13,and 15 pin as output for LED status
    GPIO.setup(11,GPIO.OUT)
    GPIO.setup(13,GPIO.OUT)
    GPIO.setup(15,GPIO.OUT)

    dweet = Dweet()#initialise dweet object


    while 1==1:#infinite loop/program loop
        GPIO.output(7,False);#turning off all LEDs
        GPIO.output(11,False);
        GPIO.output(13,False);
        GPIO.output(15,True);#LED 15 is the ON indicator. Indicates the program is running
        

        #receiving command from server
       
        try:
            rdata=dweet.latest_dweet(name=devicename) #checking for HTTP connection
        except Exception, e:#if error found
            print "Connection Error Occured" # dweet class is configured to only return a Connection Error so any error thrown is a Connection error
예제 #11
0
class Fkondenz(object):
    GPIO_DHT = 22

    DHT_HUM_ID = 0
    DHT_TEMP_ID = 0

    PROJECT_NAME = "Fluxuskondenzator"
    DWEET_ID = PROJECT_NAME + "_2017"

    DB_NAME = PROJECT_NAME
    DB_HOST = 'localhost'
    DB_USERNAME = '******'
    DB_PASSWORD = '******'

    STR_HUMIDITY = 'Humidity'
    STR_TEMPERATURE = 'Temperature'
    STR_DISTANCE = 'Distance'

    def __init__(self, _isTest):
        self.testData = None
        self.testData1 = None
        self.testData2 = None

        self.isTest = _isTest
        self.dweet = Dweet()
        try:
            self.ser = serial.Serial('/dev/ttyUSB0', 9600)
        except NameError:
            pass

    def Fkondenz(self, _isTest):
        self.isTest = _isTest
        self.dweet = Dweet()
        try:
            self.ser = serial.Serial('/dev/ttyUSB0', 9600)
        except NameError:
            pass

    def conn(self):
        """
		Creates connection with the database
		Returns connection and cursor
		:return:
		"""
        con = mdb.connect(self.DB_HOST, self.DB_USERNAME, self.DB_PASSWORD,
                          self.DB_NAME)
        cur = con.cursor()
        return cur, con

    def getSensorTypeByName(self, name):
        """
		Returns the type of the sensor by name
		:param name:
		:return:
		"""
        if self.isTest == False:
            cur, con = self.conn()
            query = "SELECT sensorTypeID FROM SensorTypes where sensorName='%s'" % (
                name)
            cur.execute(query)
            type = cur.fetchone()
            return type[0]
        else:
            return self.testData

    def getSensorValuesByID(self, id):
        """
		Returns all the values for the Sensor with id
		:param id:
		:return:
		"""
        if self.isTest == False:
            cur, con = self.conn()
            query = "SELECT date,value FROM Datas where sensorTypeID='%s'" % (
                id)
            cur.execute(query)
            values = cur.fetchall()
            listDatas = []
            for value in values:
                listDatas.append(value)
            return listDatas
        else:
            return self.testData

    def getSensorLastValueByID(self, id):
        """
		Returns the last value for the sensor with id
		:param id:
		:return:
		"""
        if self.isTest == False:
            cur, con = self.conn()
            query = "SELECT date,value FROM Datas where sensorTypeID='%s' order by date desc" % (
                id)
            cur.execute(query)
            type = cur.fetchone()
            return type[0], type[1]
        else:
            return self.testData, self.testData1

    def insertDataBySensorID(self, id, value):
        """
		Insert received or sent messages in the database
		:param id:
		:param value:
		:return:
		"""
        if self.isTest == False:
            cur, con = self.conn()
            query = "INSERT INTO Datas (sensorTypeID,value, date) VALUES ('%s', '%s', NOW())" % (
                id, value)
            cur.execute(query)
            con.commit()
        else:
            self.testData = id
            self.testData1 = value

        return

    def insertDataBySensorName(self, name, value):
        if self.isTest == False:
            print name, " ", value
            id = self.getSensorTypeByName(name)
            self.insertDataBySensorID(id, value)
        else:
            self.testData = name
            self.testData1 = value

        return

    def readDht(self):
        """
		Reads the data from the DHT sensor
		:return:
		"""
        if self.isTest == False:
            humidity, temperature = Adafruit_DHT.read_retry(
                Adafruit_DHT.AM2302, self.GPIO_DHT)
            return humidity, temperature
        else:
            return self.testData, self.testData1

    def readSensors(self):
        """
		Reads all the sensors
		:return:
		"""
        if self.isTest == False:
            resp = ""
            try:
                resp = self.ser.readline()
            except NameError:
                pass
            resp_splitted = resp.split(',')

            hum = 0
            temp = 0
            dist = 0

            for word in resp_splitted:
                if word.find(':') != -1:
                    type, data = word.split(':', 1)
                    self.insertDataBySensorName(type, data)
                    if type == self.STR_HUMIDITY:
                        hum = data
                    elif type == self.STR_TEMPERATURE:
                        temp = data
                    elif type == self.STR_DISTANCE:
                        dist = data

            return hum, temp, dist
        else:
            return self.testData, self.testData1, self.testData2

    def insertDataIntoDatabase(self, hum, temp):
        """
		Inserts the data into the database
		:param hum:
		:param temp:
		:return:
		"""
        self.insertDataBySensorID(self.DHT_HUM_ID, hum)
        self.insertDataBySensorID(self.DHT_TEMP_ID, temp)

    def sendData(self, hum, temp, dist):
        """
		Sends the sensor data to dweet.io and returns 'success' on success and 'failed' on failure
		:param hum:
		:param temp:
		:param dist:
		:return:
		"""
        try:
            resp = self.dweet.dweet_by_name(name=self.DWEET_ID,
                                            data={
                                                self.STR_HUMIDITY: hum,
                                                self.STR_TEMPERATURE: temp,
                                                self.STR_DISTANCE: dist
                                            })
            return resp['this']
        except requests.exceptions.ConnectionError:
            return "Connection error"

    def uploadToDweet(self, hum, temp, dist):
        """
		Test method wichi will print the data, send it to dweet.io and print the result
		:param hum:
		:param temp:
		:param dist:
		:return:
		"""
        if self.isTest == False:
            print "Sending"
            print "\tHumidity: ", hum
            print "\tTemperature: ", temp
            print "\tDistance: ", dist

            resp = self.sendData(hum, temp, dist)
            print "Result: " + resp + '\n'
        else:
            self.testData = "Uploaded"

    def mainLoop(self):
        """
		Loop which will read the sensors, save the data in databas and send it to dweet.io
		:return:
		"""
        while True:
            hum, temp, dist = self.readSensors()
            self.insertDataIntoDatabase(hum, temp)
            self.uploadToDweet(hum, temp, dist)
            time.sleep(1)

    def setTestData(self, _testData):
        self.testData = _testData

    def getTestData(self):
        return self.testData

    def setTestData1(self, _testData):
        self.testData1 = _testData

    def getTestData1(self):
        return self.testData1

    def setTestData2(self, _testData):
        self.testData2 = _testData

    def getTestData2(self):
        return self.testData2
예제 #12
0
 def dweet(self):
     id = self.id.replace("/", "")
     Dweet.dweet_by_name(name="{}".format(id), data=self.payload)
예제 #13
0
    (LED, 'out'),
    (RELE, 'out'),
    (TOQUE, 'in'),
)

sensibilidade = 400
temperatura = 19
dwligatoque = 0

spi = spidev.SpiDev()
spi.open(0, 0)
spi.max_speed_hz = 10000
spi.mode = 0b00
spi.bits_per_word = 8

dweet = Dweet()


def luminosidade(gpio):

    gpio.digital_write(GPIO_CS, GPIO.HIGH)
    time.sleep(0.5)
    gpio.digital_write(GPIO_CS, GPIO.LOW)
    r2 = spi.xfer2([0x01, 0xA0, 0x00])
    gpio.digital_write(GPIO_CS, GPIO.HIGH)

    adcout = (r2[1] << 8) & 0b1100000000
    adcout = adcout | (r2[2] & 0xff)

    return adcout
예제 #14
0
pins = (
    (GPIO_CS, 'out'),
    (BUTTON, 'in'),
    (RELE, 'out'),
    (LED, 'out'),
)

spi = spidev.SpiDev()
spi.open(0, 0)
spi.max_speed_hz = 10000
spi.mode = 0b00
spi.bits_per_word = 8

system_status = 1

dweet = Dweet()


def readTemp(gpio):

    gpio.digital_write(GPIO_CS, GPIO.HIGH)
    time.sleep(0.0002)
    gpio.digital_write(GPIO_CS, GPIO.LOW)
    r = spi.xfer2([0x01, 0xA0, 0x00])
    gpio.digital_write(GPIO_CS, GPIO.HIGH)

    adcout = (r[1] << 8) & 0b1100000000
    adcout = adcout | (r[2] & 0xff)
    adc_temp = (adcout * 5.0 / 1023 - 0.5) * 100
    return adc_temp
예제 #15
0
    cloud_enabled = cfg.getboolean("cloud", "enabled")
    cloud_server = cfg.get("cloud", "server")
    cloud_port = cfg.get("cloud", "port")
    cloud_url = cfg.get("cloud", "url")
    cloud_time_out = cfg.getint("cloud", "time_out")
    cloud = Cloud(cloud_enabled,
                  cloud_server,
                  cloud_port,
                  cloud_url,
                  timeout=cloud_time_out)

    enabled = cfg.getboolean("dweet", "enabled")
    dweet_server = cfg.get("dweet", "server")
    dweet_name = cfg.get("dweet", "name")
    dweet_time_out = cfg.getint("dweet", "time_out")
    dweet = Dweet(enabled, dweet_server, dweet_name, timeout=dweet_time_out)

    broker_host = cfg.get("mqtt_broker", "host")
    broker_port = cfg.get("mqtt_broker", "port")

    sub_enabled = cfg.getboolean("mqtt_subscribe", "enabled")
    sub_topics = cfg.get("mqtt_subscribe", "topics")
    sub_topics = sub_topics.split(",")
    sub_time_out = cfg.getint("mqtt_subscribe", "time_out")
    sub = MqttSub(sub_enabled,
                  broker_host,
                  broker_port,
                  sub_topics,
                  timeout=sub_time_out)
    sub.start()
    time.sleep(3)
예제 #16
0
pins = (
    (VOLUME, 'out'),
    (TEMPERATURA, 'out'),
    (SOL, 'out'),
    (IRRIGACAO, 'out'),
    (ILUMINACAO, 'out'),
    (HUMIDADE, 'out'),
)

spi = spidev.SpiDev()
spi.open(0, 0)
spi.max_speed_hz = 10000
spi.mode = 0b00
spi.bits_per_word = 8

dweet = Dweet()


def readDigital(gpio):
    digital = [0, 0]
    digital[0] = gpio.digital_read(ILUMINACAO)
    digital[1] = gpio.digital_read(IRRIGACAO)

    return digital


def writeDigital(gpio, digital):
    write = digital
    gpio.digital_write(ILUMINACAO, write[0])
    gpio.digital_write(IRRIGACAO, write[1])
예제 #17
0
pins = (
    (GPIO_CS, 'out'),
    (LED, 'out'),
    (RELE, 'out'),
)

sensibilidade = 400
status = 1

spi = spidev.SpiDev()
spi.open(0, 0)
spi.max_speed_hz = 10000
spi.mode = 0b00
spi.bits_per_word = 8

dweet = Dweet()


def luminosidade(gpio):

    gpio.digital_write(GPIO_CS, GPIO.HIGH)
    time.sleep(0.5)
    gpio.digital_write(GPIO_CS, GPIO.LOW)
    r2 = spi.xfer2([0x01, 0xA0, 0x00])
    gpio.digital_write(GPIO_CS, GPIO.HIGH)

    adcout = (r2[1] << 8) & 0b1100000000
    adcout = adcout | (r2[2] & 0xff)

    return adcout
예제 #18
0
#!/usr/bin/env python
from dweet import Dweet


if __name__ == "__main__":

    dweet = Dweet()
    
    #dweet an dweet without a thing name. Returns a a thing name in the response
    print dweet.dweet({"hello": "world"})
    
    #dweet with a thing name
    print dweet.dweet_by_name(name="test_thing", data={"hello": "world"})
    
    #get the latest dweet by thing name. Only returns one dweet.
    print dweet.latest_dweet(name="test_thing")
    
    #get all the dweets by dweet name.
    print dweet.all_dweets(name="test_thing")
예제 #19
0
파일: sender.py 프로젝트: t27/iot
#!/usr/bin/python
from dweet import Dweet
from datetime import datetime
from time import sleep
import sys


if __name__ == "__main__":
    devicename='t27_testing'
    if len(sys.argv)>1:
        devicename=sys.argv[1]

    dweet = Dweet()
    while 1==1:
        timenow=str(datetime.now())
        print dweet.dweet_by_name(name=devicename, data={ "timenowis": timenow } )
        sleep(5)
예제 #20
0
from gpio_96boards import GPIO

GPIO_CS = GPIO.gpio_id('GPIO_CS')
RELE = GPIO.gpio_id('GPIO_A')
LED = GPIO.gpio_id('GPIO_C')
BOTAO = GPIO.gpio_id('GPIO_E')

pins = ((GPIO_CS, 'out'), (RELE, 'out'), (BOTAO, 'in'), (LED, 'out'),)

spi = spidev.SpiDev()
spi.open(0,0)
spi.max_speed_hz = 10000
spi.mode = 0b00
spi.bits_per_word = 8

dweet = Dweet()

def readtemp(gpio):

	gpio.digital_write(GPIO_CS, GPIO.HIGH)
	time.sleep(0.0002)
	gpio.digital_write(GPIO_CS, GPIO.LOW)
	r = spi.xfer2([0x01, 0x80, 0x00])
	gpio.digital_write(GPIO_CS, GPIO.HIGH)
	adcout = (r[1] << 8) & 0b1100000000
	adcout = adcout | (r[2] & 0xff)		

	adc_temp = (adcout *5.0/1023-0.5)*100
	
	return adc_temp
예제 #21
0
파일: receive.py 프로젝트: t27/iot
#!/usr/bin/python
from dweet import Dweet# importing custom class for handling server communication
from datetime import datetime 
from time import sleep
import sys


if __name__ == "__main__":
    devicename='t27testing'
    if len(sys.argv)>1:
        devicename=sys.argv[1]
    prev=datetime.strptime("00:00:00","%H:%M:%S");
    dweet = Dweet()
    while 1==1:
        #timenow=str(datetime.now())
        #receiving command from server
        try:
                   rdata=dweet.latest_dweet(name=devicename)
               except Exception, e:
                   print "Connection error!!"
                   exit()
        if(rdata['this']=='failed'):
            print "No data, Check Device name"
        if(rdata['this']=='succeeded'):
            commandreceived=rdata['with'][0]['content']['command']

            #calculating timestamp of servers command
            modifieddate=rdata['with'][0]['created']
            mtime=modifieddate.split('T')[1]
            curr=datetime.strptime(mtime.split('.')[0],"%H:%M:%S");
예제 #22
0
파일: teste.py 프로젝트: bmfmata/Bruno_IoT
GPIO_CS = GPIO.gpio_id('GPIO_CS')
RELE = GPIO.gpio_id('GPIO_A')
BOTAO = GPIO.gpio_id('GPIO_C')

pins = ((GPIO_CS, 'out'), (RELE, 'out'), (BOTAO, 'in'))

#Definição de parâmetros para portas analógicas
spi = spidev.SpiDev()
spi.open(0, 0)
spi.max_speed_hz = 10000
spi.mode = 0b00
spi.bits_per_word = 8

#Declaração de uma variável Dweet para interface com sistema
# de nuvem
dweet = Dweet()

#Declaração de variáveis
alarme_bebe = 0
reset_nuvem = 0
bam_nuvem = 0
ld_nuvem = 0
estado_am = 0


#Leitura e conversão da leitura do sensor para °C
def readtemp(gpio):

    gpio.digital_write(GPIO_CS, GPIO.HIGH)
    time.sleep(0.0002)
    gpio.digital_write(GPIO_CS, GPIO.LOW)
예제 #23
0
from gpio_96boards import GPIO
from dweet import Dweet

TEMP = GPIO.gpio_id('GPIO_CS')
RELE = GPIO.gpio_id('GPIO_A')
LED = GPIO.gpio_id('GPIO_C')

pins = ((TEMP, 'in'), (RELE, 'out'), (LED, 'out'),)

spi = spidev.SpiDev()
spi.open(0,0)
spi.max_speed_hz = 10000
spi.mode = 0b00
spi.bits_per_word = 8

dweet = Dweet()


def readDigital(gpio):
	dados = [0,0]
	dados[0] = gpio.digital_read(LED)
	dados[1] = gpio.digital_read(RELE)

	return digital

def writeDigital(gpio, dados):
	escreve = dados
	gpio.digital_write(LED, escreve[0])
	gpio.digital_write(RELE, escreve[1])

	return escreve