Пример #1
0
def getBluetoothStr(wait):
        if(wait):
                print("Waiting for Commands...")
                while(True):
                        ble.println("AT+BLEUARTRX")
                        rx=ble.readLine()
                        #print(rx)
                        #print(ble.rxText)
                        if(rx=="OK\r\n"):
                                continue
                        if(ble.rxText!=""):
                                #print(ble.rxText)
                                ble.rx=""
                                break
                        ble.waitForOK()
        else:
                  ble.println("AT+BLEUARTRX")
                  rx=ble.readLine()
                        #print(rx)
                        #print(ble.rxText)
    #                    if(rx=="OK\r\n"):
   #                     #        continue
                  #if(ble.rxText!=""):
                   #  print(ble.rxText)
                          #      ble.rxText=""
                         #       break
                  ble.waitForOK()

        rxVal=ble.rxText
        ble.rxText=''
        return rxVal
Пример #2
0
def getBluetoothStr():
        print("Waiting for Commands...")
        while(True):
                ble.println("AT+BLEUARTRX")
                rx=ble.readLine()
                #print(rx)
                #print(ble.rxText)
                if(rx=="OK\r\n"):
                        continue
                if(ble.rxText!=""):
                        #print(ble.rxText)
                        ble.rx=""
                        break
                ble.waitForOK()

        return ble.rxText
Пример #3
0
def checkOut():

    """ function to prompt for location password to retrieve vehicle
        and vacate location
    """
    leave = "abcdef"
    print("\nCheck-out selected.")
    parkedCars = allParkingSpots.values()
    currentCars = [car.MAC for car in parkedCars if car.MAC != "0"]
    if currentCars:
        print("please have customer enter in their confirmation number")
        selectCar = LCDandKeypad.exit()
        for key, value in allParkingSpots.items():
            if selectCar == value.Confirmation:
                LCDandKeypad.exitWrite("retrieving car")
                currentCar = allParkingSpots[key]
                car = BLE(defaultAddr="0", defaultName="0")
                try:
                    car.Connect(MAC=currentCar.MAC)
                except Exception as e:
                    print("something went wrong: ", e)
                    break
                if car.addr != "0":
                    print("connected\n")
                    totalPrice = getPrice(currentCar.StartTime)
                    print("Customer total is ${:.2f}".format(totalPrice))
                    LCDandKeypad.exitWrite("Amount owed:",
                                           "${:.2f}".format(totalPrice))
                    if not queryYesNo("Has the customer paid? "):
                        LCDandKeypad.exitWrite("NO $ NO CAR")
                        print("Customer must pay to retrieve vehicle")
                        break
                    try:
                        print("\nRetrieving vehicle from location {}.".format(key))
                        arduinoCom(leave[int(key)-1])
                        car.sendMessage('b')
                        arduinoCom('x')
                        car.sendMessage('g')
                    except Exception as e:
                        print("something went wrong:", e)
                    blankSpot = [key, "0", "0", "0", "0", "0"]
                    dictBlankSpot = dict(zip(parkingSpot.allowedAttributes, blankSpot))
                    allParkingSpots[key] = parkingSpot(dictBlankSpot)
                    print("Location {} is now vacant.".format(key))
                    car.Disconnect()
                    del car
                    saveCustomerInfo()
                    break
                else:
                    print("couldn't connect to device")
                    break
        else:
            print("Parking pass is invalid")
            LCDandKeypad.exitWrite("Parking pass",  "is invalid")
    else:
        print("There are currently no cars parked")
Пример #4
0
def read_measurement():
    """Read serial port and surface reconstruction using machine learning model in a dead loop.

    The function calls a dead loop. In the dead loop, the sensor voltage in the serial port sent by microcontroller
    is read continuously.
    Then based on the read voltage surface vertices coordinates are computed using machine
    learning model.
    Finally, The voltage data and coordinates data are stores in global variable sensor_data_sharing
    for visualization in graph.py.
    Once the microcontroller stops get sensor data, the loop is over.

    Returns:
        None

    """
    while True:
        # temp_bytes = glv.serial_port.read(72)
        #
        # # voltage
        # temp_float = np.frombuffer(temp_bytes, dtype=np.uint16).reshape(glc.sensor_num_y, glc.sensor_num_x).astype(np.float)
        # start = time.time()
        temp_data = glc.ble.BLE_data_update()
        # print(temp_data)
        glv.sensor_v = BLE.dataDecoder(temp_data)
        print(glv.sensor_v)
        # print(time.time() - start)

        # glv.sensor_v = ((temp_data / float(glc.dacNMax)) * glc.dacRef) - glc.dacRefOffset
        # glv.sensor_v = glv.sensor_v * glv.sensor_enable

        # x-,y-,z-coordinates
        # Because the input variables of the defect sensors V12, V25 and V30 are deleted when the model is trained.
        # So the corresponding input variables of the new observation here also have to be deleted
        sensor_values_delete_zero = np.delete(glv.sensor_v,
                                              [12, 25, 30]).reshape(1, -1)

        displacement_svr = glc.svr_model.predict(sensor_values_delete_zero)
        displacement_krr = glc.svr_model.predict(sensor_values_delete_zero)
        displacement_knn = glc.svr_model.predict(sensor_values_delete_zero)
        displacement = (displacement_svr + displacement_krr +
                        displacement_knn) / 3

        x = displacement[:, :36].reshape(6, 6)
        y = displacement[:, 36:72].reshape(6, 6)
        z = displacement[:, 72:].reshape(6, 6)
        glv.sensor_xyz = [x, y, z]

        glv.sensor_data_sharing[:] = [glv.sensor_v, glv.sensor_xyz]

        if not glv.measurement_running:
            return
def getNewCoords(Coords, ListenFlag):
    temp = BLE.listen()
    temp = temp.replace('_', '')
    print(temp)
    positions = encoder.decodeMessage(temp)
    #Work on this
    for i in range(len(positions)):
        if myID is positions[i][0]:
            myCoords = positions[i]
            Coords = (myCoords[1], myCoords[2])
            ListenFlag = 0
            f = open("settings.csv", "w")
            f.write(f"L,X,Y\n{ListenFlag},{Coords[0]},{Coords[1]}")
            f.close()
    return Coords
Пример #6
0
def getNewCoords(Coords):
    global ListenFlag
    #Gets f****d up / in some type of infinite loop on the next line
    temp = BLE.listen()
    #End f*****g up
    temp = temp.replace('_', '')
    print(temp)
    positions = encoder.decodeMessage(temp)
    #Work on this
    for i in range(len(positions)):
        if myID is positions[i][0]:
            myCoords = positions[i]
            Coords = (myCoords[1], myCoords[2])
            ListenFlag = 0
            f = open(settings_address, "w")
            f.write(f"L,X,Y,ID\n{ListenFlag},{Coords[0]},{Coords[1]},{myID}")
            f.close()
    return Coords
Пример #7
0
def checkIn():

    """ function for selecting parking location and receiving
        location password
    """

    print("\nCheck-in selected")
    try:
        car = BLE(defaultAddr="0", defaultName="0")
        parkedCars = allParkingSpots.values()
        currentCars = [car.MAC for car in parkedCars if car.MAC != "0"]
        car.newConnect(currentCars)
    except Exception as e:
        print("something went wrong: ", e)
    if car.addr != "0":
        print("connected\n")
        carAttr = ["0", car.name, car.addr, str(datetime.now()), "0"]
        dictCar = dict(zip(parkingSpot.allowedAttributes, carAttr))
        newCar = parkingSpot(dictCar)
        while True:
            print("vacant locations: ")
            for key, value in allParkingSpots.items():
                if value.MAC == '0':
                    print(key)
            selectSpot = input("Please select a location: ")
            currentSpot = allParkingSpots[selectSpot]
            if selectSpot in allParkingSpots.keys() and currentSpot.MAC == "0":
                print("You have selected location {}.".format(selectSpot))
                arduinoCom(selectSpot)
                car.sendMessage('g')
                print("Generating parking pass...")
                newCar.Spot = selectSpot
                rand = newCar.Confirmation = str(randint(10000000, 99999999))
                print("Your confirmation number is {}.".format(rand))
                LCDandKeypad.entranceWrite("Confirmation #:", str(rand))
                allParkingSpots[selectSpot] = newCar
                saveCustomerInfo()
                if queryYesNo("Would you like an email or text confirmation? "):
                    sendConfirmation(newCar.Confirmation)
                break
            print("\nInvalid. Parking location is occupied or non-existant.")
        car.Disconnect()
        del car
Пример #8
0
def initBluetooth():
	print("Beginning...")
	ble.begin()
	print("Resetting...")
	ble.factoryReset()
Пример #9
0
	def receiveMessages():
		if self.device_type == 0:
			msg = BLE.listen()
Пример #10
0
import BLE

device_type = 0

# Rx Messages
# def listen(UUID = "ABC4", maxNumMessages = 5)
if device_type == 0:
	message = BLE.listen()

#Tx Messages
# def broadcast_setup()
# def broadcast(data, UUID = "ABC4", Number_of_Broadcast_Cycles = 3, Time_Between_Transmissions = 15)
if device_type:
	message = "Hello!"
	broadcast_setup() # Only need to call this once after boot (or after using listen function)
	broadcast(message)
Пример #11
0
etc.
"""

import serial
from joblib import load
import BLE as blec

# Configuration of the serial port
serialPortName = 'COM4'
serialBaudRate = 230400
serialDataBits = serial.EIGHTBITS
serialParity = serial.PARITY_NONE
serialByteOrder = 'littleEndian'
serialStopBits = serial.STOPBITS_ONE
serialTimeout = None
ble = blec.BLE()

# ADC parameter
dacRef = 2.5  # Reference voltage of the DAC/ADC on the microcontroller
dacRefOffset = dacRef / 2  # The measurement voltage is shifted up by this voltage to be able to measure negative voltage differences down to (-1) * dacRefOffset.
dacNMax = 4095  # Maximum value of a digital conversion

# Sensor array parameter
sensor_num_x = 6  # Size of the sensor matrix in x direction
sensor_num_y = 6  # Size of the sensor matrix in y direction
xMin = 0  # Minimum x index of the sensors that shall be measured
xMax = 5  # Maximum x index
yMin = 0  # Minimum y index
yMax = 5  # Maximum y index

# Get sensor parameter
Пример #12
0
import BLE
BLE.listen()
Пример #13
0
def main():
    global news_archive
    global cmd
    global SoundLevel, CurrentTemp, SongPlayer
    # getTempAndHumity()
    ### initialize
    subprocess.call(['sudo', 'insmod', './eslab/final/dht11.ko'])
    # subprocess.call(['sudo', 'insmod', './dht11.ko'])
    fanDevice = BLE.BLEdevice()
    CurrentTemp = getTemp()
    util.ChangeSoundLevel(SoundLevel)
    GPIO.setmode(GPIO.BOARD) ## Use board pin numbering
    GPIO.setup(37, GPIO.OUT) ## Setup GPIO Pin 7 to OUT
    ###
    print("Current temp is {}".format(CurrentTemp))
    print("initialize done")
    while True:
        print(">>>> command : {}".format(cmd))
        while True:
            if fanDevice.fanPower == 'on':
                tmpTemp = getTemp()
                if tmpTemp - CurrentTemp > 1.0:
                    os.system('mpv ./sounds/tempup.mp3')
                    fanDevice.speedUpFan()
                elif CurrentTemp - tmpTemp > 1.0:
                    os.system('mpv ./sounds/tempdown.mp3')
                    fanDevice.speedDownFan()

            ## listen
            print("[main] Listening")
            if DEBUG:
                print("DEBUG is on, please type your command")
                cmd = input()
            else:
                cmd = recognition.rec()
            print("command is : ",cmd)
            if cmd == 0 :
                continue
            else :
                break
        if "天氣" in cmd:
            print(">>>> command : {}".format(cmd))
            flag = 0
            for it in city_dict:
                if it in cmd:
                    city = it
                    flag = 1
                    break
            if flag == 0:
                city = '台北'
            sstr = weather_crawer.get_weather(city)
            recognition.t2speech(sstr)
            ## call craw_weather
        elif "現在" in cmd:
            if "時間" in cmd:
                sstr = getCTime()
                recognition.t2speech(sstr)
                cmd = ''
            elif "氣溫" in cmd or "溫度" in cmd or "溫濕度" in cmd:
                sstr = getTempAndHumity()
                recognition.t2speech(sstr)
                cmd = ''

        elif "新聞" in cmd:
            if news_archive == None:
                util.SayCrawingNews()
                sstr = news_crawer.craw_hot()
                news_archive = sstr
            if '第' in cmd:
                idx = util.getint(cmd)
                if idx > len(news_archive):
                    recognition.t2speech("錯誤,請再念一次")
                else:
                    print("[main] Get index : ",idx)
                    readNews(idx)
            else:
                recognition.t2speech("以下為今日的熱門新聞")
                tmp = []
                for it in sstr:
                    tmp.append(str(it['rank']) + ',' + it['title'])
                    # recognition.t2speech("{},,{}".format(it['rank'], it['title']))
                tmp = ',,'.join(tmp)
                recognition.t2speech(tmp)

        elif "關機" in cmd or "掰掰" in cmd:
            recognition.t2speech("掰掰")
            break
        elif "歌" in cmd or '音樂' in cmd:
            recognition.t2speech("請問你要聽什麼歌")
            if DEBUG:
                print("DEBUG is on, please type your command")
                quer = input()
            else:
                quer = recognition.rec()
            print(quer)
            play_music_from_youtube(quer)
        elif "風扇" in cmd or "電扇" in cmd:
            if '打開' in cmd or '關' in cmd:
                fanDevice.fanPowerSwitch()
                sstr = None
            elif '強' in cmd or '快' in cmd:
                sstr = fanDevice.speedUpFan()
            elif '弱' in cmd or '慢' in cmd:
                sstr = fanDevice.speedDownFan()
            if sstr != None:
                recognition.t2speech(sstr)
        elif "音量" in cmd or "聲音" in cmd:
            if "大" in cmd or '高' in cmd:
                if SoundLevel != 80:
                    SoundLevel +=5
                    util.ChangeSoundLevel(SoundLevel)
                    os.system('mpv ./sounds/IncreaseSound.mp3')
                else:
                    os.system('mpv ./sounds/AlreadyMaxSound.mp3')
                    # recognition.t2speech("已經是最大聲了")

            elif "小" in cmd or "低" in cmd:
                if SoundLevel != 5:
                    SoundLevel -=5
                    util.ChangeSoundLevel(SoundLevel)
                    os.system('mpv ./sounds/DecreaseSound.mp3')
                else:
                    os.system('mpv ./sounds/AlreadyMinSound.mp3')                
                    # recognition.t2speech("已經是最小聲了")
        else:
            print("cmd is none of anyone")
            print("cmd :",cmd)
            os.system('mpv ./sounds/sayagain.mp3')
        cmd=''