Esempio n. 1
0
        def StartGateway(self):
                print("Starting Bluetooth Gateway\n")
                print("Connecting the MQTT Broker")
                self.mqtt = MQTT(self.credentials)
                time.sleep(2)

                #Subscribe to the BLE Commands topic
                #print "\nSubscribing to topic: ble/" + self.gwBTMac + "/BLECommands"
                self.mqtt.SubscribeToTopic("ble/" + self.gwBTMac + "/BLECommands", self.BleCommandReceived)

                
                #Publish the gateway status message
                #print "Publishing topic: " + "ble/" + self.gwBTMac + "/BLEGatewayStatus"
                self.PublishGatewayOnlineEvent()

                time.sleep(2)

                #Register an exit handler to set the gateway offline when an exit happens
                atexit.register(self.setGatewayOffline)

                try:
                        while True:
                                self.reconcileDevices()
                                
                                #Scan for devices every two minutes
                                self.ScanForDevices()
                                time.sleep(self.credentials['scanInterval'])
                except KeyboardInterrupt:
                        print "Gateway stopping..."
Esempio n. 2
0
 def start(self):
     if self.mqtt is None:
         self.mqtt = MQTT(self.credentials)
     self.who_is(None, None, GlobalBroadcast())
     timer = threading.Timer(self.interval, self.start)
     timer.daemon = True
     timer.start()
Esempio n. 3
0
 def startNode(self):
     # server and data collection run in parallel
     cd = multiprocessing.Process(target=self.collectData())
     mqtt = multiprocessing.Process(target=MQTT())
     mqtt.start()
     cd.start()
     mqtt.join()
     cd.join()
Esempio n. 4
0
def test():
    mqtt_obj = MQTT(client_id="SSNSuperUser", host="192.168.0.120")
    mqtt_obj.client.loop_start()
    while True:
        print("Waiting for 1 second")
        time.sleep(1)
        pass
    pass
Esempio n. 5
0
 def startHead(self):
     # server, aggregator, and data collection run in parallel
     httpd = SocketServer.TCPServer(("", 8080), MyHandler)
     wb = multiprocessing.Process(target=httpd.serve_forever())
     cd = multiprocessing.Process(target=self.collectData())
     agg = multiprocessing.Process(target=self.aggregateData())
     mqtt = multiprocessing.Process(target=MQTT())
     mqtt.start()
     wb.start()
     cd.start()
     agg.start()
     mqtt.join()
     wb.join()
     cd.join()
     agg.join()
Esempio n. 6
0
from MQTT import MQTT
from WiFi import WiFi
from led_control import Control

print("Initiating...")

pycom.rgbled(0xff0000)

#Initiate LED control
led_control = Control(num_of_leds=198, initial_state=(0, 0, 0))

#Initialize MQTT
mqtt = MQTT(led_control, device_name="moon_pycom")
#Initialize WiFi and start scanning for networks
wifi = WiFi(mqtt)
Esempio n. 7
0
class BluetoothGateway:
        connectedBLEDevices = {}
        
        def __init__(self, credentials):
                self.credentials = credentials
                self.scanner = None

                self.gwBTMac = self.GetMacAddress()
                self.StartGateway()


        def GetMacAddress(self):
                #Execute the hcitool command and extract the mac address using a regular expression
                mac = re.search('hci0\s*(([0-9a-fA-F]{2}:){5}([0-9a-fA-F]{2}))', os.popen('hcitool -i hci0 dev').read()).group(1)
                return mac

        def StartGateway(self):
                print("Starting Bluetooth Gateway\n")
                print("Connecting the MQTT Broker")
                self.mqtt = MQTT(self.credentials)
                time.sleep(2)

                #Subscribe to the BLE Commands topic
                #print "\nSubscribing to topic: ble/" + self.gwBTMac + "/BLECommands"
                self.mqtt.SubscribeToTopic("ble/" + self.gwBTMac + "/BLECommands", self.BleCommandReceived)

                
                #Publish the gateway status message
                #print "Publishing topic: " + "ble/" + self.gwBTMac + "/BLEGatewayStatus"
                self.PublishGatewayOnlineEvent()

                time.sleep(2)

                #Register an exit handler to set the gateway offline when an exit happens
                atexit.register(self.setGatewayOffline)

                try:
                        while True:
                                self.reconcileDevices()
                                
                                #Scan for devices every two minutes
                                self.ScanForDevices()
                                time.sleep(self.credentials['scanInterval'])
                except KeyboardInterrupt:
                        print "Gateway stopping..."

        def reconcileDevices(self):
                #If a device is in the connectedBLEDevices dictionary has a scanned attribute of false,
                #it has gone offline. Update the device status and delete the previous device
                for key in self.connectedBLEDevices.keys():
                        if self.connectedBLEDevices[key]['scanned'] == False:
                                print "Device disconnected, deleting device", key
                                self.setDeviceStatus(self.connectedBLEDevices[key]['peripheral'], False)
                                del self.connectedBLEDevices[key]['peripheral']
                                del self.connectedBLEDevices[key]

        def setDeviceStatus(self, device, online):
                dev = {}
                dev['deviceAddress'] = device.deviceAddress
                dev['deviceType'] = device.deviceType
                dev['deviceAddrType'] = device.addrType

                if online:
                        dev['status'] = "Connected"
                        print "Setting the device to Connected"
                else:
                        dev['status'] = "Offline"
                        print "Setting the device to Offline"

                #Publish the device status message
                self.PublishMessage(json.dumps(dev), "BLEDeviceStatus",  None)

        def setGatewayOffline(self):
                #Publish the gateway status message
                print "Setting the gateway to offline"
                self.PublishGatewayOfflineEvent()

                #Give some time for the offline message to be published
                time.sleep(1)

        def ScanForDevices(self):
                #Before we re-scan again, set the scanned attribute of the existing devices to false
                for key in self.connectedBLEDevices.keys():
                        self.connectedBLEDevices[key]['scanned'] = False

                print("Scanning for devices")
                if self.scanner == None:
                        self.scanner = Scanner().withDelegate(ScanDelegate(self))

                #devices will contain an array of ScanEntry objects
                devices = self.scanner.scan(5)
                
        def PublishMessage(self, message, messageType, callback):
                if messageType == "addBLEdevice":
                        self.mqtt.PublishTopic(messageType, message, callback)
                else:
                        topic = "ble/" + self.gwBTMac + "/" + messageType
                        self.mqtt.PublishTopic(topic, message, callback)

        def PublishGatewayOnlineEvent(self):
                messageToPublish = {}
                messageToPublish["gatewayAddress"] = self.gwBTMac
                messageToPublish["status"] = "Online"

                self.PublishMessage(json.dumps(messageToPublish), "BLEGatewayStatus", None)

        def PublishGatewayOfflineEvent(self):
                messageToPublish = {}
                messageToPublish["gatewayAddress"] = self.gwBTMac
                messageToPublish["status"] = "Offline"

                self.PublishMessage(json.dumps(messageToPublish), "/BLEGatewayStatus", None)

        def PublishError(self, error):
                self.PublishMessage(error, "BLEErrors", None)

        def OnStatusPublished(self, client, userdata, mid):
                print "Gateway status set to online"        

        def BleCommandReceived(self, client, obj, message):
                arrivedMessageJSON = message.payload

                parsedMessage = {}
                try:
                        parsedMessage = json.loads(arrivedMessageJSON)
                except:
                        print "Invalid JSON received in BTLE command"
                        print(sys.exc_info())
                        self.PublishError("Invalid JSON received in BTLE command")

                deviceAddress = parsedMessage['deviceAddress']
                if parsedMessage['command'] == 'connect':
                        deviceType = parsedMessage['deviceType']
                        deviceAddrType = parsedMessage['deviceAddrType']
                        try:
                                #If the device already exists, use the existing peripheral instance
                                # and re-read the data values
                                if self.connectedBLEDevices.get(deviceAddress) == None:
                                        print "Creating new device"
                                        peripheral = BluetoothLE(deviceAddress, deviceType, deviceAddrType, self)
                                        device = {}
                                        device['peripheral'] = peripheral
                                        device['scanned'] = True
                                        self.connectedBLEDevices[deviceAddress] = device
                                else:
                                        print "Connecting to existing device"
                                        self.connectedBLEDevices[deviceAddress]['scanned'] = True
                                        self.connectedBLEDevices[deviceAddress]['peripheral'].ConnectToBLEDevice(False)

                        except BTLEException as be:
                                print("BTLEException: " + str(be))
                                self.PublishError("BTLEException: Code = " + str(be.code) + ", Message = " + be.message)
                        except:
                                print(sys.exc_info())
                                print("Could not connect to " + deviceType)
                                self.PublishError("Could not connect to " + deviceType)
                elif parsedMessage['command'] == 'read' or parsedMessage['command'] == 'readAll':
                        readDeviceAddress = parsedMessage['deviceAddress']
                        if (readDeviceAddress in self.connectedBLEDevices) == True:
                                try:
                                        if parsedMessage['command'] == 'read':
                                                self.connectedBLEDevices[readDeviceAddress]['peripheral'].ReadValue(parsedMessage['uuid'])
                                        else:
                                                self.connectedBLEDevices[readDeviceAddress]['peripheral'].ReadLoop()
                                                
                                except:
                                        print("Error reading from BLE device" + readDeviceAddress)
                                        print(sys.exc_info())
                                        self.PublishError("Error reading from BLE device " + readDeviceAddress)
                        else:
                                print(readDeviceAddress + ": No such device found. Please connect the device first and then try again")
                                self.PublishError(readDeviceAddress + \
                                        ": No such device found. Please connect the device first and then try again")
                elif parsedMessage['command'] == 'write':
                        writeDeviceAddress = parsedMessage['deviceAddress']
                        if (writeDeviceAddress in self.connectedBLEDevices) == True:
                                try:
                                        self.connectedBLEDevices[writeDeviceAddress]['peripheral'].WriteValue(parsedMessage['data'], parsedMessage['uuid'])
                                except:
                                        print("Error writing to BLE device" + deviceAddress)
                                        print(sys.exc_info())
                                        self.PublishError("Error writing to BLE device " + deviceAddress)
                        else:
                                print(writeDeviceAddress + ": No such device found. Please connect the device first and then try again")
                                self.PublishError(writeDeviceAddress + \
                                        ": No such device found. Please connect the device first and then try again")
Esempio n. 8
0
from config import AppConfig
from sensors import Laser, Button
from MQTT import MQTT

if __name__ == '__main__':
    with AppConfig() as app_config:
        laser = Laser(7)
        button = Button(12)
        mqttclient = MQTT()
        while True:
            button.listen_onclick(laser.switch)
            message = 'Laser is ON' if laser.light_state else 'Laser is OFF'
            mqttclient.pulish(topic='signals/button',
                              retain=True,
                              payload=message)
Esempio n. 9
0
def main():
    print('\nStarting SMI - Core...\n')
    os.system('systemctl stop [email protected]')
    time.sleep(3)
    print('\nLoading Meters...\n')
    loadPower = 1
    Cloud = MQTT()
    Scan = FrequencyScan()
    Frequency = AdjustParam()
    Meters = []
    Meters = DownloadMeters(Frequency)
    adjustParam = 0
    init = 1
    Flag = 1


    try:
        print('\nStarting Meters...\n')
        MeterIdx = []
        MeterIdx = StartMeters(Meters)
        while True:
            #time.sleep(15)
            metering = []
            relayValue = [0] *10
            relayIntermedValue = []
            relayInfo = []
            del relayInfo[:]
            #del relayValue[:]
            metering_lastid = 0
            iThreshold = 0.1
            iCount = 0

            for MeterIdx in Meters:
                MQTTCommand(MeterIdx, iThreshold, Flag)
                if (MeterIdx[4].meteringAvailable() == True):
                    url = "http://delso.pythonanywhere.com/SelecionarFlags%i" % (MeterIdx[0])
                    Flag = UrlResponseVerification(url)

                    metering = MeterIdx[4].meteringGet()

                    for metering_row in metering:
                    # Store metering in the database
                    # Create metering record
                        url = "http://delso.pythonanywhere.com/InsereMeterFlagNovaMedicao%iFlag%i" % (
                        MeterIdx[0], Flag)
                        resp = UrlResponseVerification(url)

                    # Get last Metering Id
                    url = "http://delso.pythonanywhere.com/LastMeteringIdRasp"
                    metering_lastid = UrlResponseVerification(url)

                    #     # Insert Data code 1 = voltage (V)
                    #     # Data code 2 = current (A)
                    #     # Data code 3 = power factor
                    #     # Data code 4 = tot wh (wh)
                    #     # Data code 5 = tot varh (varh)
                    #     # Data code 6 = Pot (W)


                    url = "http://delso.pythonanywhere.com/InserirDados/ID%i_METERINGMETERID%i__DATA1_VALUE%f__DATA2_VALUE%f__DATA3_VALUE%f__DATA4_VALUE%f__DATA5_VALUE%f" \
                          % (metering_lastid, MeterIdx[0], metering_row[1], metering_row[2], metering_row[3],
                             metering_row[4], metering_row[5])
                    resp = UrlResponseVerification(url)
					
                    VoltageMQTT = ("/Medidor/%i/Tensao") %(MeterIdx[0])
                    CorrenteMQTT = ("/Medidor/%i/Corrente") % (MeterIdx[0])
                    FPMQTT = ("/Medidor/%i/FP") % (MeterIdx[0])
                    EnergiaMQTT = ("/Medidor/%i/Energia") % (MeterIdx[0])
                    ReativaMQTT = ("/Medidor/%i/Reativa") % (MeterIdx[0])
                    #
                    Cloud.client.publish(VoltageMQTT, ("Tensão = %fV" %(metering_row[1])))
                    Cloud.client.publish(CorrenteMQTT, ("Corrente = %fA" % (metering_row[2])))
                    Cloud.client.publish(FPMQTT, ("Fator de potencia = %f" % (metering_row[3])))
                    Cloud.client.publish(EnergiaMQTT, ("Energia = %fWh" % (metering_row[4])))
                    Cloud.client.publish(ReativaMQTT, ("Energia Reativa = %fVArh" % (metering_row[5])))
                    metering = []


    except KeyboardInterrupt:
        print('Stopping SMI...\n')
        Scan.pi.set_mode(15, pigpio.ALT0)  # GPIO 15 as RX
        traceback.print_exc(file=sys.stdout)
        for MeterIdx in Meters:
            GPIO.cleanup()
            print('Stopping [%s]' % (MeterIdx[1]))
            MeterIdx[4].TurnOffPWM()
            if MeterIdx[4].isAlive(): MeterIdx[4].kill_received = True
            pid = os.getpid()
            os.kill(pid, signal.SIGKILL)

    except Exception:
        print('Stopping SMI...\n')
        Scan.pi.set_mode(15, pigpio.ALT0)  # GPIO 15 as RX
        traceback.print_exc(file=sys.stdout)
        for MeterIdx in Meters:
            GPIO.cleanup()
            print('Stopping [%s]' % (MeterIdx[1]))
            MeterIdx[4].TurnOffPWM()
            if MeterIdx[4].isAlive(): MeterIdx[4].kill_received = True
            pid = os.getpid()
            os.kill(pid, signal.SIGKILL)
def main():

    input_type = input("Enter your input type: ")
    print(input_type)


    if (input_type=="video"):
        cap = input_video()

    if (input_type=="cam"):
        cap = input_cam()


    # set a confidence threshold
    conf_threshold = 0.01

    # inference Model.onnx (downloaded)
    model ="models/Model.onnx"
    sess = rt.InferenceSession(model)

    # print("splitted string")
    # print(model.split(".")[0])

    labels_path = model.split(".")[0] + "_labels.txt"
    # print(labels_path)

    MQTT_Connect = "OFF"
    img_Segmentation = "ON"


    if (MQTT_Connect == "ON"):

    # import mqtt
        client1 = MQTT("broker.mqttdashboard.com", "smartcam", 2)

    while (True):

        # wait for 5 milliseconds
        cv2.waitKey(5)

        if (input_type == "video" or input_type == "cam"):

            # capture frame by frame
            # ret will return a boolean (True of False), wether frame is read correctly
            ret, frame = cap.read()

        # show the frame


        if (input_type == "photo"):
            frame = input_photo()
            # frame = cv2.imread('/home/thomas/Downloads/diningtable.jpg', 0)

            #segm = watershed_segmentation(frame)
            #segm.segment()


        cv2.imshow('frame', frame)
        #time.sleep(1)

        # return a single-row matrix
        # imencode makes from a 3 dimensional matrix to single column rows
        ret, enc = cv2.imencode('.jpg', frame)
        # print(ret, enc)

        # make one list [a b c d e]
        # flatten will change your rows of 1 column to columns of 1 row
        enc = enc.flatten()
        # print(enc)

        # preprocess this data
        fr = preprocess(enc.tolist())
        # infer
        p = infer(fr, sess, conf_threshold,labels_path)

        # print(len(p))
        # print only if there is an object detected
        if not len(p) == 0:

            print(p)

            if(MQTT_Connect == "ON"):



                client1.sendMessage(str(p))
Esempio n. 11
0
@app.route('/admin/cart.html')
def send_carthtml():
    return send_from_directory('', 'cart.html')


@app.route('/')
def hello_world():
    return 'Hello World!'


api.add_resource(CartAssign, '/getCart/<int:cartNum>/<deviceId>')
api.add_resource(ItemCount, '/getItemCount/<itemName>')
api.add_resource(CartUnAssign, '/giveCart/<int:cartNum>')
api.add_resource(getItemDetail, '/getDetail')
api.add_resource(GetCartDetail, '/getcartDetail')

if __name__ == '__main__':

    items = Item()
    carts = Cart()
    points = Point()

    itemRoot = ElementTree.parse("Data/Items.xml").getroot()
    cartRoot = ElementTree.parse("Data/Carts.xml").getroot()
    pointRoot = ElementTree.parse("Data/Points.xml").getroot()

    mqtt = MQTT()

    app.run(host='0.0.0.0')
Esempio n. 12
0
# Imports
import npyscreen
import logging
import threading
import queue
from Message import Frame

from tcp_server import server_thread
from MQTT import MQTT

conn_q = queue.Queue()
send_q = queue.Queue()

mqtt_inst = MQTT(send_q)


# create UI
class ServerApp(npyscreen.NPSAppManaged):
    tcp_thread = threading.Thread(target=server_thread,
                                  daemon=True,
                                  args=(
                                      conn_q,
                                      send_q,
                                  ))

    def onStart(self):
        self.tcp_thread.start()
        self.addForm("MAIN", MainForm)


class MainForm(npyscreen.Form):
Esempio n. 13
0
    DEBUG = str2bool(config['ASV']['DEBUG'])
    SENSOR = str2bool(config['ASV']['SENSOR'])
    vehicle_id = config['ASV']['id']
    mqtt_addr = config['MQTT']['broker_ip']
    default_mission_filename = config['ASV']['default_mission']

    received_mqtt_wp = [0, 0,
                        0]  # Inicializando objeto de wp desde el servidor
    asv_mode = 0  # el modo del ASV deseado
    current_asv_mode = -1  # el modo del ASV actual

    asv_mode_strs = ["STANDBY", "GUIDED", "MANUAL", "SIMPLE",
                     "RTL"]  # Strings para modos
    mqtt = MQTT(vehicle_id,
                addr=mqtt_addr,
                topics2suscribe=[f"veh{vehicle_id}"],
                on_message=on_message)

    vehicle_ip = obtener_ip_puerto()

    if verbose > 0:
        print("ASV ready to connect.")
        print(f"Starting mode:{asv_mode} {asv_mode_strs[asv_mode]}.")
        print(f"Debug set to {DEBUG}.")
        print(f"Connecting to vehicle in {vehicle_ip}")

    keep_going = True
    signal.signal(signal.SIGTERM, manejador_de_senal)

    mg = KMLMissionGenerator(default_mission_filename)
    waypoints = mg.get_mission_list()[0]
Esempio n. 14
0
        
        TemperatureStream.streamingData()
        LightStream.streamingData()
        HumidityStream.streamingData()
        
        time.sleep(5)
'''



if __name__ == "__main__":
    Device = Devices(Relay_PINS)
    Sensor = Sensors()

    
    Device_MQTT = MQTT(messageHandler=deviceHandler).get_client()
    Device_MQTT.connect('localhost', 1883)
    Device_MQTT.subscribe('Devices')
    
    Sensor_MQTT = MQTT(ClientType='python_pub').get_client()
    Sensor_MQTT.connect('localhost', 1883)
    Sensor_MQTT.subscribe('Sensors')
   
    
    print "\n\nGetting Devices Started\n"
    Device_MQTT.loop_start()
    Sensor_MQTT.loop_start()
    sensorHandler(Sensor)
    
    '''
    thread_Graph = Thread(target=graphHandler, args=(Sensor,))