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")
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)
while GPIO.input(ECHO)==0: pulse_start = time.time() while GPIO.input(ECHO)==1: pulse_end = time.time() pulse_duration = pulse_end - pulse_start #Convert distance to FillLevel #226 is Maximum read when empty by ultrasonic #40 is minimum read when full by ultrasonic distance = pulse_duration * 17150 FillLevel = ((226-distance)/(226-40))*100 FillLevel = round(FillLevel, 2) print "FillLevel:",FillLevel,"%" else: print "Lid is Open, cannot read ultrasonic sensor" FillLevel = 0 '''**************************************************************************************** Sends Data to Losant ****************************************************************************************''' device.send_state({"FillLevel": FillLevel, "LidState": LidState, "location": "47.385610, 8.518149" }) time.sleep(5)
setColor(losantconfig.OTHER_DEVICE_ID,'red') try: while True: # keep doing this forever and ever device.loop() # keeps MQTT connection alive ### Key State ### key_state = not GPIO.input(losantconfig.KEY_PIN) # False is when the key is turned, so we're flipping it for sanity's sake # state changed to turned if key_state == True and is_key_turned == 0: print('Key Turned') is_key_turned = 1 if device.is_connected(): # send the key's state via MQTT device.send_state({ "isKeyTurned": is_key_turned}) # state changed to unturned if key_state == False and is_key_turned == 1: print('Key Released') is_key_turned = 0 if device.is_connected(): # send the key's state via MQTT device.send_state({ "isKeyTurned": is_key_turned}) ### Button State ### button_state = not GPIO.input(losantconfig.BUTTON_PIN) # False is when the button is pressed, so we're flipping it for sanity's sake # state changed to pressed if button_state == True and is_button_pressed == False: print('Button Pressed')
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)
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
try: while True: # keep doing this forever and ever device.loop() # keeps MQTT connection alive ### Key State ### key_state = not GPIO.input( losantconfig.KEY_PIN ) # False is when the key is turned, so we're flipping it for sanity's sake # state changed to turned if key_state == True and is_key_turned == 0: print('Key Turned') is_key_turned = 1 if device.is_connected(): # send the key's state via MQTT device.send_state({"isKeyTurned": is_key_turned}) # state changed to unturned if key_state == False and is_key_turned == 1: print('Key Released') is_key_turned = 0 if device.is_connected(): # send the key's state via MQTT device.send_state({"isKeyTurned": is_key_turned}) ### Button State ### button_state = not GPIO.input( losantconfig.BUTTON_PIN ) # False is when the button is pressed, so we're flipping it for sanity's sake # state changed to pressed
""" 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() if device.is_connected(): # Call out to your sensor here temp = random.random() * 100 device.send_state({"temperature": temp}) time.sleep(1)
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() if device.is_connected(): # Call out to your sensor here temp = random.random() * 100 device.send_state({"temperature": temp}) time.sleep(1)
[elem[LABELS] for elem in GelliBelloi.Labels.Gruppo3.Allarmi])) ## Print created json with nice indentation #print(json.dumps(jjj, indent=4, sort_keys=True)) ## send data to startIt print('Sending data to Startit...') responseFromStartit = sendJson(dataStartit) print(responseFromStartit) ## send data to losant print('Sending data to Losant...') # invio un boolean per tracciare se acceso o spento try: deviceGenerale.send_state({"power_on": True}) except Exception as e: print(e) try: deviceGruppo1.send_state(dataLosant) except Exception as e: print(e) try: deviceGruppo2.send_state(dataLosant) except Exception as e: print(e) try: deviceGruppo3.send_state(dataLosant)
# Construct device device = Device("my-device-id", "my-access-key", "my-access-secret") def on_command(device, command): print("Command received.") print(command["name"]) print(command["payload"]) if command["name"] == "toggle": GPIO.output(led, lightStatus) # Listen for commands. device.add_event_observer("command", on_command) # Connect to Losant. device.connect(blocking=False) print("Here we go! Press CTRL+C to exit") try: while 1: device.loop() if device.is_connected(): if GPIO.input(button): device.send_state({"button": 1}) time.sleep(0.075) # Debounce button press else: time.sleep(0.03) except KeyboardInterrupt: # If CTRL+C is pressed, exit cleanly: GPIO.cleanup() # cleanup all GPIO