Exemplo n.º 1
0
class Main:
    def __init__(self, args):
        self.__init_logging()

        self.__logger.info("Going to initialize Gps()")
        self.__gps = Gps()

        self.__logger.debug("Going to read position and direction")
        start, start_bear = self.__gps.fetch_get_pos_bearing()
        self.__logger.debug("start=" + str(start))
        self.__logger.debug("start_bear=" + str(start_bear))

        destination = Point(args.lon, args.lat)

        announcer_manager = AnnouncerManager()

        self.__logger.debug("Going to initialize router")
        router = OrsRouter(start, start_bear, destination, announcer_manager)

        while self.__update_pos_wrapped(self.__gps.fetch_get_pos_bearing(), router) == False: time.sleep(config.routing['main_poll_interval'])

        self.__logger.info("Arrival at destination")

    def __update_pos_wrapped(self, pos_bear, router):
        return router.update_pos(pos_bear[0], pos_bear[1])

    def __init_logging(self):
        logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        self.__logger = logging.getLogger(__name__)
        self.__logger.setLevel("DEBUG") # level for this class only
Exemplo n.º 2
0
    def test__degreesFromString(self):
        degrees = Gps._degreesFromString("""38°59'26.348\"""")
        self.assertAlmostEqual(degrees, 38.99, 2)

        degrees = Gps._degreesFromString("""300.34°""")
        self.assertAlmostEqual(degrees, 300.34, 2)

        self.assertRaises(ValueError, Gps._degreesFromString, """300.34° """)
        self.assertRaises(ValueError,  Gps._degreesFromString, """blah""")
Exemplo n.º 3
0
def deepsleep_now():
    """ prepare scripts for graceful exit, deepsleeps if case """
    mesh.timer_kill()
    watchdog.timer_kill()
    rx_worker.timer_kill()
    ble_comm.close()
    Gps.terminate()
    mesh.statistics.save_all()
    print('Cleanup code, all Alarms cb should be stopped')
    if deepsleep_timeout > 0:
        print('Going to deepsleep for %d seconds' % deepsleep_timeout)
        time.sleep(1)
        machine.deepsleep(deepsleep_timeout * 1000)
Exemplo n.º 4
0
    def test_fromString(self):
        gps = Gps.fromString("""38°59'26.348"N, 5°24'47.948"E""")
        self.assertAlmostEqual(gps.latitude, 38.99, 2);
        self.assertEqual(gps.latitude_ref, 'N')
        self.assertAlmostEqual(gps.longtitude, 5.41, 2)
        self.assertEqual(gps.longtitude_ref, 'E')
        self.assertEqual(gps.altitude, None)

        gps = Gps.fromString("""38°59'26.348"N, 5°24'47.948"E, 254""")
        self.assertAlmostEqual(gps.latitude, 38.99, 2);
        self.assertEqual(gps.latitude_ref, 'N')
        self.assertAlmostEqual(gps.longtitude, 5.41, 2)
        self.assertEqual(gps.longtitude_ref, 'E')
        self.assertEqual(gps.altitude, 254.)

        self.assertRaises(ValueError, Gps.fromString, "blah")
Exemplo n.º 5
0
def deepsleep_now():
    """ prepare scripts for graceful exit, deepsleeps if case """
    mesh.timer_kill()
    watchdog.timer_kill()
    rx_worker.timer_kill()
    ble_comm.close()
    Gps.terminate()
    mesh.statistics.save_all()
    print('Cleanup code, all Alarms cb should be stopped')
    if new_lora_mac:
        fo = open("/flash/sys/lpwan.mac", "wb")
        mac_write = bytes([
            0, 0, 0, 0, 0, 0, (new_lora_mac >> 8) & 0xFF, new_lora_mac & 0xFF
        ])
        fo.write(mac_write)
        fo.close()
        print("Really LoRa MAC set to", new_lora_mac)
    if deepsleep_timeout > 0:
        print('Going to deepsleep for %d seconds' % deepsleep_timeout)
        time.sleep(1)
        machine.deepsleep(deepsleep_timeout * 1000)
Exemplo n.º 6
0
    def __init__(self, args):
        self.__init_logging()

        self.__logger.info("Going to initialize Gps()")
        self.__gps = Gps()

        self.__logger.debug("Going to read position and direction")
        start, start_bear = self.__gps.fetch_get_pos_bearing()
        self.__logger.debug("start=" + str(start))
        self.__logger.debug("start_bear=" + str(start_bear))

        destination = Point(args.lon, args.lat)

        announcer_manager = AnnouncerManager()

        self.__logger.debug("Going to initialize router")
        router = OrsRouter(start, start_bear, destination, announcer_manager)

        while self.__update_pos_wrapped(self.__gps.fetch_get_pos_bearing(), router) == False: time.sleep(config.routing['main_poll_interval'])

        self.__logger.info("Arrival at destination")
    def neighbors_update(self):
        """ update neigh_dict from cli:'neighbor table' """
        """ >>> print(lora.cli("neighbor table"))
        | Role | RLOC16 | Age | Avg RSSI | Last RSSI |R|S|D|N| Extended MAC     |
        +------+--------+-----+----------+-----------+-+-+-+-+------------------+
        |   C  | 0x2801 | 219 |        0 |         0 |1|1|1|1| 0000000000000005 |
        |   R  | 0x7400 |   9 |        0 |         0 |1|0|1|1| 0000000000000002 |

        """
        x = self.mesh.neighbors()
        print_debug(3, "Neighbors Table: %s" % x)

        if x is None:
            # bad read, just keep previous neigbors
            return

        # clear all pre-existing neigbors
        self.router_data = RouterData()
        self.router_data.mac = self.MAC
        self.router_data.rloc16 = self.rloc16
        self.router_data.role = self.state
        self.router_data.ts = time.time()
        self.router_data.coord = Gps.get_location()

        for nei_rec in x:
            # nei_rec = (role=3, rloc16=10240, rssi=0, age=28, mac=5)
            age = nei_rec.age
            if age > 300:
                continue  # shouln't add neighbors too old
            role = nei_rec.role
            rloc16 = nei_rec.rloc16
            # maybe we shouldn't add Leader (because this info is already available at Leader)
            # if rloc16 == self.leader_rloc():
            #   continue
            rssi = nei_rec.rssi
            mac = nei_rec.mac
            neighbor = NeighborData((
                mac,
                age,
                rloc16,
                role,
                rssi,
            ))
            self.router_data.add_neighbor(neighbor)
            #print("new Neighbor: %s"%(neighbor.to_string()))
            #except:
            #    pass
        # add own info in dict
        #self.neigh_dict[self.MAC] = (0, self.rloc16, self.state, 0)
        print_debug(3, "Neighbors: %s" % (self.router_data.to_string()))
        return
Exemplo n.º 8
0
    def __init__(self, waypointFile=None):
        """Constructor for the boat object"""
        self.arduino = Arduino()
        self.gps = Gps()
        self.xbee = Xbee()
        self._waypointN = 0
        self._waypointE = 0
        self._waypointNumber = 0
        self._waypointDist = 0
        self._waypointHeading = 0
        self._targetHeading = 0
        self._targetDistance = 0

        self.s = 0
        self.c = 0
        self.r = 250
Exemplo n.º 9
0
    def get(self):
        """Returns GPS position information or None, if not present"""
        proc = Popen(["exiv2",
                "-g", "Exif.GPSInfo.GPSAltitude",
                "-g", "Exif.GPSInfo.GPSAltitudeRef",
                "-g", "Exif.GPSInfo.GPSLatitude",
                "-g", "Exif.GPSInfo.GPSLatitudeRef",
                "-g", "Exif.GPSInfo.GPSLongitude",
                "-g", "Exif.GPSInfo.GPSLongitudeRef",
                "-g", "Exif.GPSInfo.GPSMapDatum",
                "-g", "Exif.GPSInfo.GPSVersionID",
                self._file_name], stdout=PIPE, universal_newlines=True)
        res = proc.communicate()[0]
        if proc.returncode is not 0 and proc.returncode is not 253:
            raise ExivGps.ExivError("Nonzero stare returnet from cmd: %s" % repr(proc.returncode))

        lines = res.splitlines()
        gps_lat = gps_lat_ref = None
        gps_lon = gps_lon_ref = None
        for line in lines:
            line = [l for l in line.split(' ') if l]
            line = line[0:3] + [' '.join(line[3:]), ]
            tag, form, num, val = line
            if tag == "Exif.GPSInfo.GPSLatitude":
                gps_lat = Gps._degreesFromString(val.replace('deg', '°'))
            elif tag == "Exif.GPSInfo.GPSLatitudeRef":
                gps_lat_ref = {'North': 'N', 'South': 'S', }[val]
            elif tag == "Exif.GPSInfo.GPSLongitude":
                gps_lon = Gps._degreesFromString(val.replace('deg', '°'))
            elif tag == "Exif.GPSInfo.GPSLongitudeRef":
                gps_lon_ref = {'East': 'E', 'West': 'W', }[val]
            elif tag == "Exif.GPSInfo.GPSAltitude":
                gps_alt = val
            elif tag == "Exif.GPSInfo.GPSVersionID":
                if val < "2.0.0.0":
                    raise ValueError("Unsupported GPSInfo version '%s'" % val)
            elif tag == "Exif.GPSInfo.GPSMapDatum":
                if val != "WGS-84":
                    raise ValueError("Unsupported GPSInfo Datum '%s'" % val)
            else:
                raise ValueError("Invalid exiv2 resutl: %s" % repr(res))

        gps = Gps()
        if gps_lat or gps_lat_ref:
            gps.setLatitude(gps_lat, gps_lat_ref)
        if gps_lon or gps_lon_ref:
            gps.setLongtitude(gps_lon, gps_lon_ref)

        return gps
    def __init__(self, data=None):
        self.mac = 0
        self.rloc16 = 0
        self.role = 0
        self.ts = 0
        self.dict = {}
        self.pack_index_last = 0
        self.coord = Gps.get_location()

        if data is None:
            return

        datatype = str(type(data))
        if datatype == "<class 'bytes'>":
            self._init_bytes(data)
        elif datatype == "<class 'NeighborData'>":
            self._init_neighbordata(data)
Exemplo n.º 11
0
    def process(self, file_name):
        exivGps = ExivGps(file_name)
        try:
            gps = exivGps.get()
            gps = gps or "N/A"
        except ExivGps.ExivError:
            print("Failed to get exif information, skipping: '%s'" % file_name)
            return

        tabs = 6 - divmod((len(file_name) + 2 + 7), 8)[0]
        if tabs < 0:
            tabs = 0
        tabs = "\t" * tabs
        print("'%s'%s - [%s] : " % (file_name, tabs, str(gps)), end="", flush=True)
        newGps = stdin.readline().strip()
        if newGps:
            newGps = Gps.fromString(newGps, gps)
            exivGps.set(newGps)
Exemplo n.º 12
0
def main():

    # Bootsplash anzeigen
    # und 1sek warten. Wichtig: in dieser Zeit hat man die Möglichkeit über serial ein neues Programm hochzuladen
    # Beim ESP32 ist das nicht mehr wichtig, da dieser zwei serial Schnittstellen hat.
    display = Display(scl=4, sda=0)
    display.println("RSSI")
    display.println("Location")
    display.println("Logger")
    display.println("")
    # display.print_dot()

    # Systeme konfigurieren
    try:

        # nur zum Testen
        # wlan = network.WLAN(network.STA_IF)
        # wlan.active(True)
        # wlan.connect('Freifunk')
        # while not wlan.isconnected():
        # 	display.print_dot()
        # 	time.sleep(0.5)
        # display.println(str(wlan.status('rssi')))
        # time.sleep(10)

        display.println("===CONF START==")
        display.println("scan wlan")
        # Wlan Objekt erstellen, dass selbständig einen scan macht und das stärkste Freifunk zurück gibt.
        # display.print_dot()
        wlan = Wlan("Freifunk")
        # display.println(wlan.ff_ap_bssid)
        wlan.connect()

        display.println("connect")
        #display.println(ubinascii.hexlify(wlan.ff_list[0][1])+str(wlan.ff_list[0][3]))
        while not wlan.isconnected():
            display.print_dot()
            time.sleep(0.5)

        gps = Gps()

        s = 0.1

        display.println("init uart 9600")
        display.print_dot()
        uart = Uart(0, 9600)
        time.sleep(s)

        display.println("set baud 115200")
        display.print_dot()
        uart.send_command(b'PMTK251,115200')
        time.sleep(s)

        display.println("init UART 115200")
        display.print_dot()
        uart = Uart(0, 115200)
        time.sleep(s)

        display.println("set 2Hz")
        display.print_dot()
        uart.send_command(b'PMTK220,500')
        time.sleep(s)

        display.println("set RMC, GGA")
        display.print_dot()
        uart.send_command(b'PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,00')
        time.sleep(s)

        display.println("===CONF END===")

        while True:
            line = uart.readline()
            # display.println(str(line))
            gps.refresh(line)
            quality = False
            if wlan.isconnected() and int(
                    gps.sats) > 7 and gps.is_fix and float(gps.hdop) < 2:
                quality = True

            if not (wlan.isconnected()):
                # display.println("")
                # display.println("lost wlan :(")
                # display.println("reconnect...")
                wlan.reconnect()
            # else:
            display.print_info(gps, quality, wlan)
            # display.println(str(wlan.wlan.status('rssi')))
            time.sleep(0.1)

    except Exception as ex:
        display.println(repr(ex))
        for e in ex.args:
            display.println(e[:16])
            time.sleep(1)
            display.println(e[16:32])
            time.sleep(1)
            display.println(e[32:48])
        display.println("")
        time.sleep(10)
Exemplo n.º 13
0
class Ui_MainWindow():

    def __init__(self):
        self.a=Gps()
        self.setupUi(MainWindow)
    '''
        Setting up UI
    '''
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 480)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(0, 0, 800, 480))
        self.label.setText("")
        self.label.setPixmap(QtGui.QPixmap("normal.png"))
        self.label.setScaledContents(True)
        self.label.setObjectName("label")
        self.msgBox = QtWidgets.QLabel(self.centralwidget)
        self.msgBox.setGeometry(QtCore.QRect(50,10,711,31))
        font= QtGui.QFont()
        font.setPointSize(20)
        self.msgBox.setFont(font)
        self.msgBox.setStyleSheet("color:rgb(255,255,255)")
        self.msgBox.setTextFormat(QtCore.Qt.AutoText)
        self.msgBox.setScaledContents(True)
        self.msgBox.setObjectName("msgBox")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 22))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
        
    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))

    '''
        very 50ms this method will get the current distance from the Hazardous area/intersection
    '''
    def getDistance(self):
        self.temp=self.a.getLocation()# stores current location in self.temp
        threshold=900.0000 #This is the threshold value in meter that user wants to have visual alarm before he/she enters into the Hazardous area.
        data = [500,600,700,800,900,1000]#Random numers describing the number of accident occured in listed 5 intersections accordingly

        if self.temp:
            self.distanceHB = Haversine(self.temp,Haversine.HomerBlock)#stores current distance from Homerwatson/Block line intersection
            self.distanceFW = Haversine(self.temp,Haversine.FairwayWilson)#stores current distance from Fairway/Wilson intersection
            self.distanceHBishop = Haversine(self.temp,Haversine.HasplarBishop)#stores current distance from Hasplar/Bishop intersectiomn
            self.distanceHM = Haversine(self.temp,Haversine.HasplarMaple)#stores current distance from haslpar/maple intersection
            self.distanceHQ = Haversine(self.temp,Haversine.HasplarQueen)#stores current distance from hasplar/Queen intersection
            '''
                Storing all the distance in one dictionary
            '''
            self.dict1= {"Homer Block":self.distanceHB.m(),"Fairview Wilson":self.distanceFW.m(),"Hasplar Bishop":self.distanceHBishop.m(),\
                    "Hasplar Maple":self.distanceHM.m(),"Hasplar Queen":self.distanceHQ.m()}
            print("_____________________________________________")


            '''
                conditioning for visual alarm 
            '''
            if self.distanceHB.m() < threshold or self.distanceFW.m() < threshold or self.distanceHBishop.m() < threshold or \
                    self.distanceHM.m() < threshold or self.distanceHQ.m() <threshold:
               print("\nHazardous Area Ahead\n")
               self.label.setPixmap(QtGui.QPixmap("warning.png"))
               if self.distanceHB.m() <  threshold:
                   self.msgBox.setText(str(data[0])+" "+"Accidents happend at the next intersection")
               elif self.distanceFW.m() <threshold:
                   self.msgBox.setText(str(data[1])+" "+"Accidents happend at the next intersection")
               elif self.distanceHBishop.m() < threshold:
                   self.msgBox.setText(str(data[2])+" "+"Accidents happend at the next intersection")
               elif self.distanceHM.m() <threshold:
                   self.msgBox.setText(str(data[3])+" "+"Accidents happend at the next intersection")
               elif self.distanceHQ.m() < threshold:
                   self.msgBox.setText(str(data[4])+" "+"Accidents happend at the next intersection") 
              
            else:
                print("\n you are safe\n")
                self.label.setPixmap(QtGui.QPixmap("normal.png"))
                self.msgBox.setText("You are good to go !!!")

            '''
                Printing all Keys and values from the disctionary on the shell
            '''
            for x in self.dict1:
                print(self.dict1,"\n")
                if self.dict1[x]<threshold:
                    print(x,"->",self.dict1[x])
Exemplo n.º 14
0
Arquivo: main.py Projeto: aewens/gps
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# 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.

if __name__ == '__main__':
    parser = ArgumentParser(prog="gps.py")
    parser.add_argument("profile_name", dest="user", nargs="?", type=str,
        help="Your GitHub profile name")
    args = parser.parse_args()
    user = args.user
    if not user:
        user = input("Profile's name: ")
        
    if len(user) == 0:
        print("ERROR: No username was provided!")
        quit(1)

    g = Gps()
    g.gps_for(user)

    print(g.formatted_res())
Exemplo n.º 15
0
    iodef.init()

    if config.hw_rev >= 3:
        import ble
        import ble_gatt_dsc as ble_gatt
        ble.init_ble()

    crypto = Crypto()

    message = Message(crypto, config, heartbeat_message)
    message.start()

    radio = Radio("/dev/serial0", config, message, heartbeat_radio)
    radio.start()

    gps = Gps()
    gps.start()

    if config.hw_rev < 3:
        display = Display(message, version, config, revision,
                          heartbeat_display)
        display.start()

        ui = UI(display, message, crypto, radio, config, heartbeat_ui)
        ui.start()
        ui.splash()

    if config.hw_rev >= 3:
        dscGatt = ble_gatt.DscGatt(quitdsc, message, config, radio)
        dscGatt.start()
    """
Exemplo n.º 16
0
    def process(self, arg1, arg2):
        last_mesh_pairs = []
        last_mesh_mac_list = []
        last_mesh_node_info = {}

        try:
            while True:
                time.sleep(.1)
                cmd = input('>')

                if cmd == 'ip':
                    print(self.mesh.ip())

                elif cmd == 'mac':
                    # read/write LoRa MAC address
                    try:
                        id = int(
                            input('(new LoRa MAC (0-64k) [Enter for read])<'))
                    except:
                        print(self.mesh.mesh.mesh.MAC)
                        continue
                    id = id & 0xFFFF  # just 2B value
                    # it's actually set in main.py (main thread)
                    print("LoRa MAC set to", id)
                    self.sleep(1, id)  # force restart

                elif cmd == 'mml':
                    mesh_mac_list = self.mesh.get_mesh_mac_list()
                    if len(mesh_mac_list) > 0:
                        last_mesh_mac_list = mesh_mac_list
                    print('mesh_mac_list ', json.dumps(last_mesh_mac_list))

                elif cmd == 'self':
                    node_info = self.mesh.get_node_info()
                    print("self info:", node_info)

                elif cmd == 'mni':
                    for mac in last_mesh_mac_list:
                        node_info = self.mesh.get_node_info(mac)
                        time.sleep(.5)
                        if len(node_info) > 0:
                            last_mesh_node_info[mac] = node_info
                    print('last_mesh_node_info',
                          json.dumps(last_mesh_node_info))

                elif cmd == 'mp':
                    mesh_pairs = self.mesh.get_mesh_pairs()
                    if len(mesh_pairs) > 0:
                        last_mesh_pairs = mesh_pairs
                    print('last_mesh_pairs', json.dumps(last_mesh_pairs))

                elif cmd == 's':
                    try:
                        to = int(input('(to)<'))
                        # typ = input('(type, 0=text, 1=file, Enter for text)<')
                        # if not typ:
                        #     typ = 0
                        # else:
                        #     typ = int(typ)
                        txt = input('(message)<')
                    except:
                        continue
                    data = {
                        'to': to,
                        # 'ty': 0,
                        'b': txt,
                        'id': 12345,
                        'ts': int(time.time()),
                    }
                    print(self.mesh.send_message(data))

                elif cmd == 'ws':
                    to = int(input('(to)<'))
                    try:
                        id = int(input('(id, default 12345)<'))
                    except:
                        id = 12345
                    print(self.mesh.mesage_was_ack(to, id))

                elif cmd == 'rm':
                    print(self.mesh.get_rcv_message())

                elif cmd == 'gps':
                    try:
                        lat = float(input('(lat [Enter for read])<'))
                        lon = float(input('(lon)<'))
                    except:
                        print("Gps:", (Gps.lat, Gps.lon))
                        continue

                    Gps.set_location(lat, lon)
                    print("Gps:", (Gps.lat, Gps.lon))

                elif cmd == 'sleep':
                    try:
                        timeout = int(input('(time[sec])<'))
                    except:
                        continue
                    if self.sleep:
                        self.sleep(timeout)

                # elif cmd == "ble":
                #     # reset BLE connection
                #     self.ble_comm.restart()

                # elif cmd == "stat":
                #     # do some statistics
                #     # data = []
                #     # data[0] = {'mac':6, 'n':3, 't':30, 's1':0, 's2':0}
                #     # data[0] = {'mac':6, 'n':3, 't':30, 's1':5, 's2':10}
                #     # data[2] = {'mac':6, 'n':30, 't':60, 's1':10, 's2':45}
                #     # for line in data:
                #     #     print()
                #     # print("1 = {'mac':6, 'n':30, 't':60, 's1':10, 's2':45}<'")
                #     # print("2 = {'mac':6, 'n':30, 't':60, 's1':10, 's2':45}<'")
                #     # print("3 = {'mac':6, 'n':30, 't':60, 's1':10, 's2':45}<'")
                #     # id = int(input('(choice 1-..)<'))
                #     data = {'mac':6, 'n':3, 't':60, 's1':3, 's2':8}
                #     res = self.mesh.statistics_start(data)
                #     print("ok? ", res)

                # elif cmd == "stat?":
                #     try:
                #         id = int(input('(id [Enter for all])<'))
                #     except:
                #         id = 0
                #     res = self.mesh.statistics_get(id)
                #     print("ok? ", res)

                elif cmd == "rst":
                    print("Mesh Reset NVM settings ... ")
                    self.mesh.mesh.mesh.mesh.deinit()
                    if self.sleep:
                        self.sleep(1)

                # elif cmd == "pyb":
                #     # print("Pybytes debug menu, Pybytes connection is ", Pybytes_wrap.is_connected())
                #     state = 1
                #     timeout = 120
                #     try:
                #         state = int(input('(Debug 0=stop, 1=start [Default start])<'))
                #     except:
                #         pass
                #     try:
                #         timeout = int(input('(Pybytes timeout [Default 120 sec])<'))
                #     except:
                #         pass
                #     self.mesh.pybytes_config((state == 1), timeout)

                elif cmd == "br":
                    state = 2  # default display BR
                    try:
                        state = int(
                            input(
                                '(state 0=Disable, 1=Enable, 2=Display [Default Display])<'
                            ))
                    except:
                        pass

                    if state == 2:
                        print("Border Router state: ",
                              self.mesh.mesh.mesh.mesh.border_router())
                    elif state == 1:
                        # Enable BR
                        prio = 0  # default normal priority
                        try:
                            prio = int(
                                input(
                                    '(priority -1=Low, 0=Normal or 1=High [Default Normal])<'
                                ))
                        except:
                            pass
                        self.mesh.br_set(True, prio, self.new_br_message_cb)
                    else:
                        # disable BR function
                        self.mesh.br_set(False)

                elif cmd == "brs":
                    """ send data to BR """
                    ip_default = "1:2:3::4"
                    port = 5555
                    try:
                        payload = input("(message<)")
                        ip = input(
                            "(IP destination, Mesh-external [Default: 1:2:3::4])<"
                        )
                        if len(ip) == 0:
                            ip = ip_default
                        port = int(
                            input("(port destination [Default: 5555])<"))
                    except:
                        pass
                    data = {'ip': ip, 'port': port, 'b': payload}
                    print("Send BR message:", data)
                    self.mesh.send_message(data)

                elif cmd == "buf":
                    print("Buffer info:",
                          self.mesh.mesh.mesh.mesh.cli("bufferinfo"))

                elif cmd == "ot":
                    cli = input('(openthread cli)<')
                    print(self.mesh.mesh.mesh.mesh.cli(cli))

                elif cmd == "debug":
                    ret = input('(debug level[0-5])<')
                    try:
                        level = int(ret)
                        self.mesh.debug_level(level)
                    except:
                        print_debug(1, "error parsing")

                elif cmd == "config":
                    print(self.mesh.config)

                else:
                    print("List of available commands")
                    print("ip - display current IPv6 unicast addresses")
                    print("mac - set or display the current LoRa MAC address")
                    print("self - display all info about current node")
                    print(
                        "mml - display the Mesh Mac List (MAC of all nodes inside this Mesh), also inquires Leader"
                    )
                    print(
                        "mp - display the Mesh Pairs (Pairs of all nodes connections), also inquires Leader"
                    )
                    print("s - send message")
                    print("ws - verifies if message sent was acknowledged")
                    print("rm - verifies if any message was received")
                    print("sleep - deep-sleep")
                    # print("stat - start statistics")
                    # print("stat? - display statistics")
                    print(
                        "br - enable/disable or display the current Border Router functionality"
                    )
                    print("brs - send packet for Mesh-external, to BR, if any")
                    print("rst - reset NOW, including NVM Pymesh IPv6")
                    print("buf - display buffer info")
                    print("ot - sends command to openthread internal CLI")
                    print("debug - set debug level")
                    print("config - print config file contents")
                    print("gps - get/set location coordinates")

        except KeyboardInterrupt:
            print('cli Got Ctrl-C')
        except Exception as e:
            sys.print_exception(e)
        finally:
            print('cli finally')
            self.sleep(0)
Exemplo n.º 17
0
ble_comm = ble.BleCommunication(str(mesh.mesh.mesh.mac_short))


def ble_on_disconnect():
    rpc_handler = RPCHandler(rx_worker, tx_worker, mesh, ble_comm)


ble_comm.on_disconnect = ble_on_disconnect

rx_worker = RXWorker(ble_comm)
tx_worker = TXWorker(ble_comm)

rpc_handler = RPCHandler(rx_worker, tx_worker, mesh, ble_comm)

Gps.init_static()

kill_all = False
deepsleep_timeout = 0
new_lora_mac = None
watchdog = Watchdog(meshaging, mesh)


def deepsleep_now():
    """ prepare scripts for graceful exit, deepsleeps if case """
    mesh.timer_kill()
    watchdog.timer_kill()
    rx_worker.timer_kill()
    ble_comm.close()
    Gps.terminate()
    mesh.statistics.save_all()
Exemplo n.º 18
0
 def set_gps(self, latitude, longitude):
     print('settings gps!')
     Gps.set_location(latitude, longitude)
Exemplo n.º 19
0
 def set_gps(self, lng, lat):
     print('settings gps!')
     Gps.set_location(lat, lng)
Exemplo n.º 20
0
 def __init__(self):
     self.a=Gps()
     self.setupUi(MainWindow)
Exemplo n.º 21
0
ble_comm = ble.BleCommunication(mesh.mesh.mesh.MAC)


def ble_on_disconnect():
    rpc_handler = RPCHandler(rx_worker, tx_worker, mesh, ble_comm)


ble_comm.on_disconnect = ble_on_disconnect

rx_worker = RXWorker(ble_comm)
tx_worker = TXWorker(ble_comm)

rpc_handler = RPCHandler(rx_worker, tx_worker, mesh, ble_comm)

Gps.init_static()

print("done !")

last_mesh_pairs = []
last_mesh_mac_list = []
last_mesh_node_info = {}

watchdog = Watchdog(meshaging, mesh)

try:
    while True:

        # print("============ MAIN LOOP >>>>>>>>>>>")
        # t0 = time.ticks_ms()
        # mesh_mac_list = mesh.get_mesh_mac_list()