コード例 #1
0
def init(deviceId, key, secret):
	global device
	
	# Construct device
	device = Device(deviceId, key, secret)

	# Connect to Losant.
	device.connect(blocking=False)
コード例 #2
0
    def __init__(self, my_device_id, my_app_access_key, my_app_access_secret):
        threading.Thread.__init__(self)
        self.my_device_id = my_device_id
        self.my_app_access_key = my_app_access_key
        self.my_app_access_secret = my_app_access_secret

        # Construct Losant device
        self.device = Device(self.my_device_id, self.my_app_access_key,
                             self.my_app_access_secret)

        self.callback = None
コード例 #3
0
 def __init__(self):
     try:
         self.deviceGenerale = Device(DEVICE_ID_GENERALE, APP_KEY,
                                      APP_SECRET)
         self.deviceGruppo1 = Device(DEVICE_ID_GRUPPO_1, APP_KEY,
                                     APP_SECRET)
         self.deviceGruppo2 = Device(DEVICE_ID_GRUPPO_2, APP_KEY,
                                     APP_SECRET)
         self.deviceGruppo3 = Device(DEVICE_ID_GRUPPO_3, APP_KEY,
                                     APP_SECRET)
     except:
         print('Error connecting losant')
コード例 #4
0
class LosantClient(threading.Thread):

    def __init__(self, my_device_id, my_app_access_key, my_app_access_secret):
        threading.Thread.__init__(self)
        self.my_device_id         = my_device_id
        self.my_app_access_key    = my_app_access_key
        self.my_app_access_secret = my_app_access_secret

        # Construct Losant device
        self.device = Device(self.my_device_id,
                        self.my_app_access_key,
                        self.my_app_access_secret)

        self.callback = None

    def set_callback(self, callback):
        self.callback = callback

    def run(self):
        # Connect to Losant and leave the connection open
        self.device.add_event_observer("command", self.on_command)
        self.device.connect(blocking=True)


    def sendDeviceState(self, name, value):
        print("Sending Device State")
        self.device.send_state( {str(name) : value} )

    def on_command(self, device, command):
        print(command["name"] + " command received.")

        if command["name"] == "toggle":
            self.callback(command)
            print("Do something")
コード例 #5
0
ファイル: index.py プロジェクト: rons4/workflow-node-catalog
# Based on this article: https://docs.losant.com/getting-started/boards/getting-started-with-raspberry-pi

import json
from gpiozero import LED, Button  # Import GPIO library: https://gpiozero.readthedocs.io/en/stable/
from time import sleep
from losantmqtt import Device  # Import Losant library: https://github.com/Losant/losant-mqtt-python

led_gpio = 23
button_gpio = 4

led = LED(led_gpio)
button = Button(button_gpio, pull_up=False)

# Construct Losant device
device = Device("my-device-id", "my-app-access-key", "my-app-access-secret")


def on_command(device, command):
    print(command["name"] + " command received.")

    # Listen for the gpioControl. This name configured in Losant
    if command["name"] == "toggle":
        # toggle the LED
        led.toggle()
    if command["name"] == "switch_on":
        # toggle the LED
        led.on()
    if command["name"] == "switch_off":
        # toggle the LED
        led.off()
コード例 #6
0
ファイル: basic.py プロジェクト: grobalex/losant-mqtt-python
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

import time
import random
from losantmqtt import Device

# Construct device
device = Device("my-device-id", "my-app-access-key", "my-app-access-secret")


def on_command(my_device, command):
    print("Command received.")
    print(command["name"])
    print(command["payload"])


# Listen for commands.
device.add_event_observer("command", on_command)

# Connect to Losant.
device.connect(blocking=False)

# Send temperature once every second.
コード例 #7
0
import json
from gpiozero import LED, Button  # Import GPIO library: https://gpiozero.readthedocs.io/en/stable/
from time import sleep
from losantmqtt import Device  # Import Losant library: https://github.com/Losant/losant-mqtt-python

led_gpio = 23
button_gpio = 4

led = LED(led_gpio)
button = Button(button_gpio, pull_up=False)

# Construct Losant device
# device = Device("my-device-id", "my-app-access-key", "my-app-access-secret")
device = Device(
    "5bcda0385b2d0a0007732966", "057e62f0-b547-42ee-8cfe-2150907ffada",
    "8a5e9b37f2be9d91df377cc2d526be35867d9dd97da517b674e0e93fb0e90c5a")


def on_command(device, command):
    print(command["name"] + " command received.")

    # Listen for the gpioControl. This name configured in Losant
    if command["name"] == "toggle":
        # toggle the LED
        led.toggle()
    if command["name"] == "switch_on":
        # toggle the LED
        led.on()
    if command["name"] == "switch_off":
        # toggle the LED
コード例 #8
0
 def setUp(self):
     self.device = Device("device_id", "device_key", "device_secret")
コード例 #9
0
ファイル: AQ.py プロジェクト: jakejcarroll/piAQ
    from pms5003 import PMS5003, ReadTimeoutError
from bme280 import BME280
try:
    from smbus2 import SMBus
except ImportError:
    from smbus import SMBus
import atexit
import ads1015
import RPi.GPIO as GPIO
from enviroplus import gas

from losantmqtt import Device

# construct losant device
device = Device(
    "5e11e6330ac5cc0007fc1265", "0ac1cea1-a88d-4a4f-a209-55411611f9d9",
    "b5196aaacf877f153a86c08084c00cc85cac70402452d6e9f466e3b63bb7b671")

pms5003 = PMS5003()


def pm1():
    readings = pms5003.read()
    pm1_reading = (readings.pm_ug_per_m3(1.0))
    pm1_reading = "{:.0f}".format(pm1_reading)
    return int(pm1_reading)
    pm1_reading.flush()


def pm25():
    readings = pms5003.read()
コード例 #10
0
import time
from losantmqtt import Device
from bluetooth.ble import DiscoveryService

# Construct device
device = Device("my-device-id", "my-app-access-key", "my-app-access-secret")

def on_command(device, command):
    print("Command received.")
    print(command["name"])
    print(command["payload"])

# Listen for commands.
device.add_event_observer("command", on_command)

# Connect to Losant.
device.connect(blocking=False)

# Send device_name once every second.
while True:
    service = DiscoveryService()
    devices = service.discover(2)

    for address, name in devices.items():
        print("name: {}, address: {}".format(name, address))
    device.send_state({"devices" : devices.items()})

    time.sleep(1)
コード例 #11
0
import time
import random
from losantmqtt import Device


# event_type values: int, bool, none
devices = {
    "5ee4ecc26cdf8d000610bd05": {
        "name": "Temp Sensor",
        "device": Device(
            "5ee4ecc26cdf8d000610bd05",
            "cf8bdf2b-8843-4710-95df-66793d7238d9",
            "b178891f59a5d77a643cc0f4a541bb6136d9845b3512fab537025353864ffb3b"
        ),
        "sensor_attribute_key": "temp",
        "event_type": "int",
        "command_handler": lambda name, device, event_name, event_value:
        print("Got command", name, event_name, event_value),
    },
    "5ee4ed79f0e1080007ca6ab8": {
        "name": "AC",
        "device": Device(
            "5ee4ed79f0e1080007ca6ab8",
            "09379aee-d26a-497b-996d-fa85dfb44c73",
            "2e9c09fde5581e41f65a95898f28bd1f14dc8fdd5e45b51ca659bedcfaa84ec1"
        ),
        "sensor_attribute_key": "ACSwitch",
        "event_type": "none",
        "command_handler": lambda name, device, event_name, event_value:
            print("Got command", name, event_name, event_value),
    },
コード例 #12
0
ファイル: basic.py プロジェクト: Losant/losant-mqtt-python
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

import time
import random
from losantmqtt import Device

# Construct device
device = Device("my-device-id", "my-app-access-key", "my-app-access-secret")

def on_command(my_device, command):
    print("Command received.")
    print(command["name"])
    print(command["payload"])

# Listen for commands.
device.add_event_observer("command", on_command)

# Connect to Losant.
device.connect(blocking=False)

# Send temperature once every second.
while True:
    device.loop()
コード例 #13
0
ファイル: index.py プロジェクト: davisr18/lightsOnRep
#documented/edited by Roslyn Davis
import json
from gpiozero import LED, Button  # Import GPIO library: https://gpiozero.readthedocs.io/en/stable/
from time import sleep
from losantmqtt import Device  # Import Losant library: https://github.com/Losant/losant-mqtt-python

#you can find these numbers on GPIO pin chart
led_gpio = 23
button_gpio = 21

led = LED(led_gpio)
button = Button(button_gpio, pull_up=False)  #boolean that turns light on/off

# Construct Losant device. Has device id, key and secret
device = Device(
    "5ade4994753ea500075d9f37", "9e7ab66e-208e-4684-a4fb-e56dc1e8f277",
    "ec79c25175bf081905ec4cfd0c9d80744502fc3d2e6c9474b61adc97f4147ff7")


def on_command(device, command):
    print(command["name"] + " command received.")

    # Listen for the gpioControl. This name configured in Losant
    if command["name"] == "toggle":
        # toggle the LED
        led.toggle()


def sendDeviceState():
    print("Sending Device State")
    device.send_state({"button": True})
コード例 #14
0
# Get available servers on localhost
available_servers = opc.servers()

# Open Server
opc.connect(SERVER_NAME)

## read a GROUP of variable - opcGrops e' un array di stringhe
#res = readGroupData( opcGroups )

## connect to losant
# Construct Losant device
try:
    print('Connectiong to Losant...')
    #losantDevice   = Device(DEVICE_ID,          APP_KEY, APP_SECRET)
    deviceGenerale = Device(DEVICE_ID_GENERALE, APP_KEY, APP_SECRET)
    deviceGruppo1 = Device(DEVICE_ID_GRUPPO_1, APP_KEY, APP_SECRET)
    deviceGruppo2 = Device(DEVICE_ID_GRUPPO_2, APP_KEY, APP_SECRET)
    deviceGruppo3 = Device(DEVICE_ID_GRUPPO_3, APP_KEY, APP_SECRET)

    #losantDevice.connect(blocking=False)
    deviceGenerale.connect(blocking=False)
    deviceGruppo1.connect(blocking=False)
    deviceGruppo2.connect(blocking=False)
    deviceGruppo3.connect(blocking=False)

    # Listen for commands.
    #deviceGenerale.add_event_observer("command", on_command)
    print('done')
except:
    print('Error connecting losant')
コード例 #15
0

def activateSolenoid(PIN):
    GPIO.setmode(GPIO.BCM)
    GPIO.setwarnings(False)
    GPIO.setup(PIN, GPIO.OUT)
    GPIO.output(PIN, GPIO.LOW)
    print("UNLOCKED")
    sleep(6)
    GPIO.cleanup()
    print("LOCKED")


# Construct Losant device
device = Device(
    "5a00bfc943f88f00078e3937", "d7ff9bec-fd52-41f0-ac8f-1337e657b9c7",
    "01d41ec9fd8f5e6b69bd77b53f7de0c4d9afa1d829f95ec455af6e269567a0cb")

nfcUIDs = ["c4  e4  53  12", "04  66  c8  b2  a6  4a  81"]


def nfcReader():
    result = [
        i.strip() for i in os.popen(
            r"nfc-poll | grep UID | sed 's/^.*: //'").readlines()
    ]
    returnValue = str(result[-1])
    result = []
    print "UID: ", returnValue
    if returnValue in nfcUIDs:
        response = 1
コード例 #16
0
        new_color = 'blue'  #default offline
        if (keyStatus == 'engaged'):
            new_color = 'green'
        if (keyStatus == 'disengaged'):
            new_color = 'red'
        setColor(deviceId, new_color)
    if (command["name"] == "btnPressedAnim"):
        animColor = 'red'  # assume failure
        if (command["payload"]
                and command["payload"]["status"] == "succeeded"):
            animColor = 'green'  #yay!
        statusBlink(animColor, 150, 7)


# Construct device
device = Device(losantconfig.MY_DEVICE_ID, losantconfig.ACCESS_KEY,
                losantconfig.ACCESS_SECRET)
# Listen for commands.
device.add_event_observer("command", on_command)
# Connect to Losant.
device.connect(blocking=False)

#### REST setup ###
client = Client()
creds = {
    'deviceId': losantconfig.MY_DEVICE_ID,
    'key': losantconfig.ACCESS_KEY,
    'secret': losantconfig.ACCESS_SECRET
}
# Connect via REST and save the response for future connections
rest_response = client.auth.authenticate_device(credentials=creds)
client.auth_token = rest_response['token']
コード例 #17
0
class Losant:
    ## Losant

    def __init__(self):
        try:
            self.deviceGenerale = Device(DEVICE_ID_GENERALE, APP_KEY,
                                         APP_SECRET)
            self.deviceGruppo1 = Device(DEVICE_ID_GRUPPO_1, APP_KEY,
                                        APP_SECRET)
            self.deviceGruppo2 = Device(DEVICE_ID_GRUPPO_2, APP_KEY,
                                        APP_SECRET)
            self.deviceGruppo3 = Device(DEVICE_ID_GRUPPO_3, APP_KEY,
                                        APP_SECRET)
        except:
            print('Error connecting losant')

    def connect(self):
        try:
            print('Connectiong to Losant...')
            self.deviceGenerale.connect(blocking=False)
            self.deviceGruppo1.connect(blocking=False)
            self.deviceGruppo2.connect(blocking=False)
            self.deviceGruppo3.connect(blocking=False)
            print('done')
        except:
            print('Error connecting losant')

    def sendData(self, data):
        try:
            losantDevice.send_state(data)

            # invio un boolean per tracciare se acceso o spento
            deviceGenerale.send_state({"power_on": True})
            deviceGruppo1.send_state(data)
            deviceGruppo2.send_state(data)
            deviceGruppo3.send_state(data)
        except:
            print("Problem occurred sending data tot losant.")

    def notifyPlcIsOff(self):
        try:
            self.deviceGenerale.send_state({"power_on": False})
        except:
            print("Problem occurred notifing off state to losant")

    def on_command(device, command):
        print(command["name"] + " command received.")

        # Listen for the gpioControl. This name configured in Losant
        if command["name"] == "reset_all":
            resetAll()
        elif command["name"] == "reset_gruppo_1":
            resetGruppo(1)
        elif command["name"] == "reset_gruppo_2":
            resetGruppo(2)
        elif command["name"] == "reset_gruppo_3":
            resetGruppo(3)

    def resetAll(self):
        self.global_var_1 = 'foo'

    def resetGruppo(self, numeroGruppo):
        if numeroGruppo == 1: reg = REGISTRO_DI_RESET_GRUPPO_1
        if numeroGruppo == 2: reg = REGISTRO_DI_RESET_GRUPPO_2
        if numeroGruppo == 3: reg = REGISTRO_DI_RESET_GRUPPO_3

        val = None

        try:
            val = opc.write((reg, 1))
            time.sleep(1.0)
        except OpenOPC.TimeoutError:
            print("TimeoutError occured.")

        return val
コード例 #18
0
ファイル: index.py プロジェクト: Baron-OConnor/Raspberry_Pi
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import encoders
from gpiozero import LED, MotionSensor  # Import GPIO library: https://gpiozero.readthedocs.io/en/stable/
from time import sleep
from losantmqtt import Device  # Import Losant library: https://github.com/Losant/losant-mqtt-python

led_gpio = 23
pir_gpio = 20

led = LED(led_gpio)
pir = MotionSensor(pir_gpio, pull_up=False)
# Construct Losant device
device = Device(
    "5ada7f66e304ec0006542ace", "43207a25-c78c-4b87-9349-1578dbd80686",
    "633f190871e9909a262bd31f2570b184c01abbd158af2a30deae104d2faadcfb")

fromaddr = "*****@*****.**"
toaddr = "*****@*****.**"

msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "PIR Active w/ Image"
body = "Image captured"


def on_command(device, command):
    print(command["name"] + " command received.")
コード例 #19
0
                ct = datetime.datetime.now()
                ctt = str(ct.hour) + " " + str(ct.minute) + " " + str(
                    ct.second)
                print(ctt, st, et)
                print("loop", lightStatus1)
                led.setValue(0)
                time.sleep(1)
                if lightStatus1 == 1:
                    led.setValue(1)
                    break
            led.setValue(1)


# Construct device
device = Device(
    "5b1e42dc96c2ca000681d529", "69cd072f-8e6a-4636-84d9-35b4835695d0",
    "909d124b7d435ec6a220267336c1de670498b6d27bb5515a9c0ce6f3a9a657ec")


# Called when a Losant Device Command is received.
def on_command(device, command):
    global lightStatus
    global lightStatus1
    print("Command received.")

    #data = json.dumps({'state':lightStatus,'timestamp':time.time()})        # json is a recommended data format
    #client.publish("sigmaway/akrd/db2"
    #                   "",data)
    #client.publish(topic="sigmaway", payload=data,qos=0,retain=False)
    client.on_publish = on_publish
    print(command["name"])
コード例 #20
0
led_gpio = 23
spot_gpio = 24
button_gpio = 21

led = LED(led_gpio)
spot = LED(spot_gpio)
button = Button(button_gpio, pull_up=False)
active = False

#def ledBlink():
#	led.toggle()
#	sleep(1)

# Construct Losant device
device = Device(
    "5aff0b811255b000068e852e", "1dc7bfa3-60ac-4529-a184-c45d13e08e4e",
    "aee15624a75f3dc2d36459f33771b6b1f7911c5176e284e9eece22715e7d6aa1")

#def main_loop():
#	mythread = LedThread()
#	mythread.start()

#class LedThread(Thread):
#
#	def _init_(self):
#		super(LedThread, self)._init_()
#		self._keepgoing = True
#	def run(self):
#		while (self._keepgoing):
#			print 'Blink'
#			time.sleep(0.5)
コード例 #21
0
        keyStatus = command["payload"]["keyStatus"]
        print(deviceId)
        print(keyStatus)
        new_color = 'blue' #default offline
        if(keyStatus == 'engaged'):
            new_color = 'green'
        if(keyStatus == 'disengaged'):
            new_color = 'red'
        setColor(deviceId, new_color)
    if(command["name"] == "btnPressedAnim"):
        animColor = 'red' # assume failure
        if(command["payload"] and command["payload"]["status"] == "succeeded"):
            animColor = 'green' #yay!
        statusBlink(animColor, 150, 7)
# Construct device
device = Device(losantconfig.MY_DEVICE_ID, losantconfig.ACCESS_KEY, losantconfig.ACCESS_SECRET)
# Listen for commands.
device.add_event_observer("command", on_command)
# Connect to Losant.
device.connect(blocking=False)


#### REST setup ###
client = Client()
creds = {
    'deviceId': losantconfig.MY_DEVICE_ID,
    'key': losantconfig.ACCESS_KEY,
    'secret': losantconfig.ACCESS_SECRET
}
# Connect via REST and save the response for future connections
rest_response = client.auth.authenticate_device(credentials=creds)
コード例 #22
0
from losantmqtt import Device

ACCESS_KEY = 'eed2fd5b-8219-4b18-a858-cdf345185cd6'
ACCESS_SECRET = '1d8c634d39551e13a6da838bfdc152cdc43e10362bca3a888cbfc2a411020dd3'
DEVICE_ID = '5e2ec7308eb4af0006ecd530'

DELAY = 1.0

# Construct Losant device
device = Device(DEVICE_ID, ACCESS_KEY, ACCESS_SECRET)


def sendDataToLosant(data):
    print("Sending to Losant...")
    device.send_state(data)


def connectToLosant():
    # Connect to Losant and leave the connection open
    global device
    device.connect(blocking=False)
コード例 #23
0
GPIO.output(TRIG, False)
GPIO.output(alarmOut,False)
    

'''****************************************************************************************
Connect to Losant using your own Device Id Key, app access key and app access secret. 

By Default, the function is:

device = Device("my-device-id", "my-app-access-key", "my-app-access-secret")

Check it out at: https://docs.losant.com/mqtt/python/
****************************************************************************************'''

# Construct device
device = Device("YourDeviceIDHere", "Your Access Key", "Your Access Secret")

def on_command(device, command):
    print("Command received.")
    print(command["name"])
    print(command["payload"])

# Listen for commands.
device.add_event_observer("command", on_command)

# Connect to Losant.
device.connect(blocking=False)


'''****************************************************************************************
While True loop to run for eternity.. or Answer = 42, you decide
コード例 #24
0
class TestDevice(unittest.TestCase):

    def setUp(self):
        self.device = Device("device_id", "device_key", "device_secret")

    def test_correct_props(self):
        self.assertEqual(self.device._device_id, "device_id")
        self.assertEqual(self.device._key, "device_key")
        self.assertEqual(self.device._secret, "device_secret")
        self.assertEqual(self.device._secure, True)
        self.assertEqual(self.device._command_topic(), "losant/device_id/command")
        self.assertEqual(self.device._state_topic(), "losant/device_id/state")

    def test_add_remove_observer(self):
        self.event_fired = 0
        def on_event(device):
            self.assertEqual(device, self.device)
            self.event_fired += 1
        self.device.add_event_observer("test", on_event)
        self.device._fire_event("test")
        self.assertEqual(self.event_fired, 1)
        self.device.remove_event_observer("test", on_event)
        self.device._fire_event("test")
        self.assertEqual(self.event_fired, 1)

    def test_send_state(self):
        self.device._mqtt_client = MqttMock()
        calls = self.device._mqtt_client.publish_calls
        self.assertEqual(len(calls), 0)
        result = self.device.send_state({"one": "two"}, 1234)
        self.assertEqual(result, True)
        calls = self.device._mqtt_client.publish_calls
        self.assertEqual(len(calls), 1)
        self.assertEqual(calls[0][0], "losant/device_id/state")
        expected_payload = '{"data": {"one": "two"}, "time": 1234}'
        self.assertEqual(calls[0][1], expected_payload)

    def test_receive_command(self):
        self.cmd_msg = None
        def on_command(device, msg):
            self.assertEqual(device, self.device)
            self.cmd_msg = msg
        self.device.add_event_observer("command", on_command)
        mock = MsgMock('{"name":"start","payload":{"one":[2,3]},"time":{"$date":"2016-06-01T01:09:51.145Z"}}')
        self.device._cb_client_command(None, None, mock)
        self.assertEqual(self.cmd_msg["name"], "start")
        self.assertEqual(self.cmd_msg["payload"], {"one": [2, 3]})
        self.assertEqual(self.cmd_msg["time"].microsecond, 145000)
        self.assertEqual(calendar.timegm(self.cmd_msg["time"].utctimetuple()), 1464743391.0)