Ejemplo n.º 1
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")
Ejemplo n.º 2
0
def init(deviceId, key, secret):
	global device
	
	# Construct device
	device = Device(deviceId, key, secret)

	# Connect to Losant.
	device.connect(blocking=False)
Ejemplo n.º 3
0
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
****************************************************************************************'''

# Send values once every second.
while True:
    device.loop()
    if device.is_connected():
        
        # Read Lid state to check if its open
        LidState = GPIO.input(LIDCOVER)
              
        # Ultrasonic Sensor Read only if Lid is closed
        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']
app_id = rest_response['applicationId']

Ejemplo n.º 5
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
Ejemplo n.º 6
0
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()


def sendDeviceState():
    print("Sending Device State")
    device.send_state({"button": True})


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

print("Listening for device commands")

button.when_pressed = sendDeviceState  # Send device state when button is pressed

# Connect to Losant and leave the connection open
device.connect(blocking=True)
Ejemplo n.º 7
0
## 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')

ALARM_RESET_TH = 10
resetAlarmsCounter = 0

## stampo le dimensioni dei
while (True):