Ejemplo n.º 1
0
def test_googlemaps_precision(location):
    m = mh.to_maiden(*location.latlon, precision=4)
    assert m == location.maiden

    g4 = mh.google_maps(m)

    m1 = mh.to_maiden(*location.latlon)
    assert m1 == location.maiden[:6]

    g1 = mh.google_maps(m1)
    assert g4 != g1
Ejemplo n.º 2
0
def make_response(worldwide, flag, slist):
    res = []

    if (flag & 0x02) == 2:
        return ({'totalCount': len(slist)})

    gsifl = (flag & 0x01) == 1

    for r in slist:
        if not r:
            return res
        else:
            if worldwide:
                (summit_id, lat, lng, pts, elev, name, desc) = r
                gl = mh.to_maiden(float(lat), float(lng), precision=4)
                res.append({
                    'code': summit_id,
                    'lat': lat,
                    'lon': lng,
                    'maidenhead': gl,
                    'pts': pts,
                    'elev': elev,
                    'name': name,
                    'name_k': '',
                    'desc': desc
                })
            else:
                (summit_id, lat, lng, pts, elev, name, desc, name_k,
                 desc_k) = r
                if (gsifl):
                    gsi = gsi_rev_geocoder(lat, lng, True)
                else:
                    gsi = None
                gl = mh.to_maiden(float(lat), float(lng), precision=4)
                res.append({
                    'code': summit_id,
                    'lat': lat,
                    'lon': lng,
                    'maidenhead': gl,
                    'pts': pts,
                    'elev': elev,
                    'name': name_k,
                    'name_k': name,
                    'desc': desc_k,
                    'gsi_info': gsi
                })

    return res
Ejemplo n.º 3
0
def convert_latlon_to_maidenhead(
    latitude: float, longitude: float, output_precision: int = 4
):
    """
    Convert latitude / longitude coordinates to Maidenhead coordinates

    Parameters
    ==========
    latitude : 'float'
        Latitude value
    longitude : 'float'
        Longitude value
    output_precision: 'int'
        Output precision for lat/lon

    Returns
    =======
    maidenhead_coordinates: 'str'
        Maidenhead coordinates for the given lat/lon with
        the specified precision
    """

    maidenhead_coordinates = None
    if abs(int(latitude)) <= 90 and abs(int(longitude)) <= 180:
        maidenhead_coordinates = maidenhead.to_maiden(
            latitude, longitude, precision=output_precision
        )
    return maidenhead_coordinates
Ejemplo n.º 4
0
def main(
    loc: str | tuple[float, float],
    precision: int = 3,
    url: bool = False,
    center: bool = False,
) -> str | tuple[float, float]:
    if isinstance(loc, str):  # maidenhead
        maiden = copy(loc)
        loc = maidenhead.to_location(loc, center)
        print(f"{loc[0]:.4f} {loc[1]:.4f}")
    elif len(loc) == 2:  # lat lon
        if isinstance(loc[0], str):
            loc = (float(loc), float(loc))
        maiden = maidenhead.to_maiden(*loc, precision=precision)
        print(maiden)
        loc = maiden
    else:
        raise ValueError("specify Maidenhead grid (single string) or lat lon (with space between)")

    if url:
        uri = maidenhead.google_maps(maiden, center)
        print(uri)
        return uri

    return loc
Ejemplo n.º 5
0
def gsi_rev_geocoder(lat, lng, elev):
    try:
        if not lat or not lng:
            raise Exception
        pos = '?lat=' + str(lat) + '&lon=' + str(lng)
        rev_uri = gsi_endpoint['revgeocode'] + pos
        elev_uri = gsi_endpoint['elevation'] + pos + '&outtype=JSON'

        gl = mh.to_maiden(float(lat), float(lng), precision=4)

        r_get = requests.get(rev_uri)
        if r_get.status_code == 200:
            res = r_get.json()
            if res:
                muni = str(int(res['results']['muniCd']))
                r = lookup_muniCode(muni)
                r['addr1'] = res['results']['lv01Nm']
            else:
                r = {
                    'pref': '',
                    'addr2': '',
                    'addr1': '',
                    'type': 'JCC',
                    'jcc': ':Unkown',
                    'jcc_text': ''
                }
            if elev:
                r_get = requests.get(elev_uri)
                if r_get.status_code == 200:
                    res = r_get.json()
                    if res:
                        r['elevation'] = res['elevation']
                        r['hsrc'] = res['hsrc']
            r['maidenhead'] = gl
            r['errors'] = 'OK'
            return r
        else:
            r = {
                'pref': '',
                'addr2': '',
                'addr1': '',
                'type': 'JCC',
                'jcc': ':Unkown',
                'jcc_text': ''
            }
            if elev:
                r_get = requests.get(elev_uri)
                if r_get.status_code == 200:
                    res = r_get.json()
                    if res:
                        r['elevation'] = res['elevation']
                        r['hsrc'] = res['hsrc']
                        r['maidenhead'] = gl
                        r['errors'] = 'OK'
                        return r
            raise Exception
    except Exception as err:
        return {'errors': 'parameter out of range'}
Ejemplo n.º 6
0
    def __get_maidenhead(self, level):
        """
        Get maidenhead coordinates given an accuracy level.
        """

        mh_resp = {'grid': None, 'lock': False}
        loc = self.__get_gps_location()

        if loc['lock']:
            mh_resp['lock'] = True
            mh_resp['grid'] = mh.to_maiden(loc['lat'],
                                           loc['lon'],
                                           precision=level)

        return mh_resp
Ejemplo n.º 7
0
def main():
    p = argparse.ArgumentParser(description="convert to / from Maidenhead locator")
    p.add_argument(
        "loc", help="Maidenhead grid (single string) or lat lon (with space between)", nargs="+"
    )
    p.add_argument("-p", "--precision", help="maidenhead precision", type=int, default=3)
    p.add_argument("-u", "--url", help="also output Google Maps URL", action="store_true")
    args = p.parse_args()

    if len(args.loc) == 1:  # maidenhead
        maiden = args.loc[0]
        print('{:.4f} {:.4f}'.format(*maidenhead.to_location(maiden)))
    elif len(args.loc) == 2:  # lat lon
        maiden = maidenhead.to_maiden(*map(float, args.loc), precision=args.precision)
        print(maiden)
    else:
        raise SystemExit("specify Maidenhead grid (single string) or lat lon (with space between)")

    if args.url:
        print(maidenhead.google_maps(maiden))
Ejemplo n.º 8
0
    def setLocationFromWindows(self):
        wt = 5 # Wait time -- I purposefully make it wait before the shell command
        accuracy = 3 

        #while True:
        #time.sleep(wt)
        pshellcomm = ['powershell']
        pshellcomm.append('add-type -assemblyname system.device; '\
                              '$loc = new-object system.device.location.geocoordinatewatcher;'\
                              '$loc.start(); '\
                              'while(($loc.status -ne "Ready") -and ($loc.permission -ne "Denied")) '\
                              '{start-sleep -milliseconds 100}; '\
                              '$acc = %d; '\
                            'while($loc.position.location.horizontalaccuracy -gt $acc) '\
                            '{start-sleep -milliseconds 100; $acc = [math]::Round($acc*1.5)}; '\
                            '$loc.position.location.latitude; '\
                            '$loc.position.location.longitude; '\
                            '$loc.position.location.horizontalaccuracy; '\
                            '$loc.stop()' %(accuracy))

        p = sp.Popen(pshellcomm, stdin = sp.PIPE, stdout = sp.PIPE, stderr = sp.STDOUT, text=True)
        (out, err) = p.communicate()
        out = re.split('\n', out)

        lat = float(out[0])
        lon = float(out[1])
        radius = int(out[2])

        if self.showOutput:
            print(lat, lon, radius)

        self.current_lat=lat
        self.current_lon=lon
        self.mhGrid = mh.to_maiden(lat,lon,precision=self.location_precision)

        if self.showOutput:
            print(self.mhGrid) 
Ejemplo n.º 9
0
    def run(self):
        try:
            while self.readGPS:

                if self.locator_precision == None:
                    self.locator_precision = 4

                data = self.session.next()
                if self.showdebug == 1:
                    print(data)
                if data['class'] == 'TPV':

                    lat = getattr(data, 'lat', 0.0)
                    lon = getattr(data, 'lon', 0.0)
                    #
                    gpstime = getattr(data, 'time', 0)
                    #
                    if gpstime == "0":
                        self.currentmhgrid = "No Fix"
                    else:
                        latlon = (lat, lon)

                        grid = mh.to_maiden(lat,
                                            lon,
                                            precision=self.locator_precision)

                        self.current_lat = lat
                        self.current_lon = lon
                        self.current_gpstime = gpstime
                        self.current_mhgrid = grid
                        currentMHGrid = grid

        except (KeyboardInterrupt, SystemExit):  #when you press ctrl+c
            print("\nKilling Thread...")
            self.runFlag = False
            self.join()  # wait for the thread to finish what it's doing
            print("Done.\nExiting.")
Ejemplo n.º 10
0
def main(loc: T.Union[str, T.Sequence[float]],
         precision: int = 3,
         url: bool = False):
    if isinstance(loc, str):  # maidenhead
        maiden = copy(loc)
        loc = maidenhead.to_location(loc)
        print(f"{loc[0]:.4f} {loc[1]:.4f}")
    elif len(loc) == 2:  # lat lon
        if isinstance(loc[0], str):
            loc = list(map(float, loc))
        maiden = maidenhead.to_maiden(*loc, precision=precision)
        print(maiden)
        loc = maiden
    else:
        raise ValueError(
            "specify Maidenhead grid (single string) or lat lon (with space between)"
        )

    if url:
        uri = maidenhead.google_maps(maiden)
        print(uri)
        return uri

    return loc
Ejemplo n.º 11
0
def main(config_path):
    try:

        config = read_json_io(config_path)
        print(config)

        wu_json = get_current_observation(config['wu_api_id'],
                                          config['wu_api_key'])

        # -- Initialize --
        stdscr = curses.initscr()  # initialize curses screen
        curses.start_color()
        curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE)
        curses.init_pair(2, curses.COLOR_YELLOW, curses.COLOR_BLACK)
        curses.init_pair(3, curses.COLOR_GREEN, curses.COLOR_BLACK)

        curses.noecho()  # turn off auto echoing of keypress on to screen
        curses.cbreak()  # enter break mode where pressing Enter key
        stdscr.nodelay(1)
        #  after keystroke is not required for it to register
        stdscr.keypad(
            1)  # enable special Key values such as curses.KEY_LEFT etc

        # -- Perform an action with Screen --
        stdscr.border(0)
        stdscr.addstr(0, 3, ' Ham Radio Dashboard v0.1 ', curses.color_pair(3))
        stdscr.addstr(5, 5, config['callsign'], curses.color_pair(1))
        stdscr.addstr(8, 5, 'LAT/LNG:', curses.A_NORMAL)
        stdscr.addstr(
            8, 15,
            str(config['station_geo'][0]) + ', ' +
            str(config['station_geo'][1]), curses.A_NORMAL)

        iaru_loc = mh.to_maiden(config['station_geo'][0],
                                config['station_geo'][1])
        stdscr.addstr(9, 5, 'IARU Loc:', curses.A_NORMAL)
        stdscr.addstr(9, 15, iaru_loc, curses.A_NORMAL)

        elev = config['elev']
        stdscr.addstr(10, 5, 'Elev.:', curses.A_NORMAL)
        stdscr.addstr(10, 15, str(elev) + ' m', curses.A_NORMAL)

        stdscr.addstr(stdscr.getmaxyx()[0] - 2, 2, 'Q - Quit',
                      curses.color_pair(3))

        begin_x = 50
        begin_y = 4
        height = 16
        width = 50
        win = curses.newwin(height, width, begin_y, begin_x)

        win.border(0)

        win.box()
        win.addstr(
            0, 3, " Weather Station: " +
            str(wu_json['observations'][0]['stationID']) + " ",
            curses.color_pair(2))
        print_wu_data(win, config['wu_api_id'], config['wu_api_key'])

        seconds = 0
        while True:
            stdscr.refresh()
            win.refresh()
            stdscr.addstr(6, 5, 'UTC: ', curses.A_NORMAL)
            stdscr.addstr(7, 5, 'LOCAL: ', curses.A_NORMAL)
            now = datetime.now()
            local = pytz.timezone("America/Sao_Paulo")
            local_dt = local.localize(now, is_dst=None)
            utc_dt = local_dt.astimezone(pytz.utc)

            utc_date_time = utc_dt.strftime("%m/%d/%Y, %H:%M:%S")
            stdscr.addstr(6, 15, utc_date_time, curses.A_NORMAL)
            local_date_time = local_dt.strftime("%m/%d/%Y, %H:%M:%S")
            stdscr.addstr(7, 15, local_date_time, curses.A_NORMAL)

            # stay in this loop till the user presses 'q'
            ch = stdscr.getch()
            if ch == ord('q') or ch == ord('Q'):
                break
            stdscr.timeout(1000)
            seconds = seconds + 1
            if seconds == (20 * 60):
                seconds = 0
                print_wu_data(win, config['wu_api_id'], config['wu_api_key'])
        # -- End of user code --

    except:
        traceback.print_exc()  # print trace back log of the error

    finally:
        # --- Cleanup on exit ---
        stdscr.keypad(0)
        curses.echo()
        curses.nocbreak()
        curses.endwin()
Ejemplo n.º 12
0
def test_latlon2maiden(location):
    m = maidenhead.to_maiden(*location.latlon)
    assert m == location.maiden[:6]
Ejemplo n.º 13
0
def json_to_maiden(json_str):
    gr = json.loads(json_str)
    return mh.to_maiden(gr['lat'], gr['lon'])
Ejemplo n.º 14
0
with open(configdir + '/config.yaml') as f:
    cfg = yaml.load(f, Loader=yaml.FullLoader)

address = ' '.join(sys.argv[1:])
geolocator = Nominatim(user_agent="ON3URE_hamtools")
try:
    location = geolocator.geocode(address)

    locator1 = latlong_to_locator(cfg['qth']['latitude'],
                                  cfg['qth']['longitude'])
    locator2 = latlong_to_locator(location.latitude, location.longitude)

    heading = calculate_heading(locator1, locator2)
    longpath = calculate_heading_longpath(locator1, locator2)
    maidenhead = mh.to_maiden(location.latitude, location.longitude)

    print(
        fg('blue') + '-=' + fg('turquoise_4') + attr('bold') +
        "QTE: Bearing lookup" + attr('reset') + fg('blue') + '=-' +
        attr('reset'))
    print(fg('#884444') + attr('bold') + 'Address: ', end="")
    print(fg('dark_sea_green_3b') + location.address)
    print(fg('#884444') + attr('bold') + 'Latitude: ', end="")
    print(fg('dark_sea_green_3b') + "%.1f°" % location.latitude, end="")
    print(fg('#884444') + attr('bold') + ' Longitude: ', end="")
    print(fg('dark_sea_green_3b') + "%.1f°" % location.longitude, end="")
    print(fg('#884444') + attr('bold') + ' Grid square: ', end="")
    print(fg('dark_sea_green_3b') + maidenhead)
    print()
    print(fg('#884444') + attr('bold') + 'Heading: ', end="")
Ejemplo n.º 15
0
        if Cent == "20":
            print('Old Header String Detected')
            # Have old header format - pull the data fields out
            #2020-05-15,N8OBJ Macedonia Ohio EN91fh,LB GPSDO,41.3219273, -81.5047731, 284.5
            UTCDTZ = Header[0] + "T000000Z"
            print('UTCDTZ now =', UTCDTZ)
            #get this stations Node #
            node = Snode
            #print('Node =', node)
            Lat = Header[3]
            #print('Lat =', Lat)
            Long = Header[4]
            #print('Long =', Long)
            Elv = Header[5]
            #print('Elev =', Elv)
            GridSq = mh.to_maiden(float(Lat), float(Long))
            #print('GridSq =', GridSq)
            citystate = Header[1]
            #print('City State =', citystate)
            radioid = SRID
            #print('Radio ID =', radioid)
            #beacon = "unknown"
            #print('Beacon =', beacon)

        else:
            print("Unknown header format - I give up...")
            dataFile.close()
            sys.exit(0)

    dataFile.close()
Ejemplo n.º 16
0
            Done = 1
            LLEdat[2] = Elev  # assign new value to array
            print('Elevation Saved as ' + Elev)
        else:
            print('Wrong min Elevation Length of ' + str(elvlth) + ' for ' +
                  Elev)
            Done = 0

################################################################
# Check if need to update Lat, Long, Elev and Gridsquare
if changeLLE > 0:
    # there was a change made - save it
    nlat = float(Lat)
    nlong = float(Long)
    #print(nlat, nlong, nelev)
    GridSqr = mh.to_maiden(nlat,
                           nlong)  # create gridsquare from Lat /Long info
    print('\nSaving New Coordinate Info')
    print('Latitude: ' + Lat)
    print('Longitude: ' + Long)
    print('Elevation: ' + Elev)
    with open(LLEPath, 'w') as LLEFile:
        LatLonElv = Lat + ',' + Long + ',' + Elev + '\n'  # create default Lat Long Elv Numbers
        LLEFile.write(LatLonElv)  #write default LAt Long Elev
        LLEFile.close()
    os.chmod(LLEPath, mode=0o764)  # set the permissions to 764

    ################################################################
    #write new Grid Square
    GSPath = InfoDir + "GridSqr"
    with open(GSPath, 'w') as GSFile:
        GSFile.write(GridSqr + '\n')
Ejemplo n.º 17
0
    def run(self):
        print('listening on', ':'.join(map(str, self.listen)))
        self.sock = socket(AF_INET, SOCK_STREAM)
        self.sock.connect(self.listen)
        self.listening = True
        try:
            while self.listening:
                # self.showoutput=True
                # content, addr = self.sock.recvfrom(65500)
                #if self.showoutput:
                #    print(content)
                datalist = self.sock.recv(PACKET_SIZE)
                #if self.showoutput:
                ##    print(datalist)
                self.i = self.i + 1

                #print(datalist.decode())
                nmeaRows = datalist.decode().split("\r\n")

                for row in nmeaRows:
                    if self.showoutput:
                        print(row)

                # print (nmeaRows)

                    gpsData = row.split(",")

                    # self.showoutput=False

                    #if self.showoutput:
                    #    print(str(self.i))
                    #    print(gpsData)

                    if self.showoutput:
                        print(gpsData[0])

                    if len(gpsData) < 7:
                        continue
                    if gpsData[0] == TIME_SENTENCE:
                        gpsTime = gpsData
                        self.current_epoch = 1
                        if self.showoutput:
                            print("TIME===" + self.current_epoch)
                    #if gpsData[0]==ALT_SENTENCE:
                    #    #$GPGGA
                    #    gpsAlt = gpsData[9]
                    #    gpsUnit = gpsData[10]
                    #    self.altitude = gpsAlt+gpsUnit
                    #    if self.showoutput:
                    #        print("ALTITUDE==="+self.altitude)
                    if gpsData[0] == SENTENCE or gpsData[
                            0] == ALTERNATE_SENTENCE:
                        if gpsData[2] == 'A':
                            if self.showoutput:
                                print(gpsData)
                            gpsTime = gpsData[1]
                            #print(gpsTime)
                            gpsLat = float(gpsData[3])
                            gpsN = gpsData[4]
                            gpsLon = float(gpsData[5])
                            gpsE = gpsData[6]

                            if (gpsN == SOUTH):
                                gpsLat = -gpsLat

                            latDeg = int(gpsLat / 100)
                            latMin = gpsLat - latDeg * 100
                            lat = latDeg + latMin / 60

                            if (gpsE == WEST):
                                gpsLon = -gpsLon

                            lonDeg = int(gpsLon / 100)
                            lonMin = gpsLon - lonDeg * 100
                            lon = lonDeg + lonMin / 60

                            self.mhGrid = mh.to_maiden(
                                lat, lon, precision=self.location_precision)
                            self.current_lat = lat
                            self.current_lon = lon

                            if self.showoutput:
                                print("Maidenhead Grid " + self.mhGrid)

        except (KeyboardInterrupt, SystemExit):
            self.setReadGPS(False)
            self.join()
            print("Done.\nClosing GPS Listener.")

        finally:
            self.sock.close()
Ejemplo n.º 18
0
    def run(self):
        showoutput=self.showOutput
        
        try:
            while self.readGPS:
                line = self.gps.readline()
    
                gpsData = line.decode().split(",")

                if showoutput==1:
                    print(gpsData)
                
                if gpsData[0]==time_sentence:
                    gpsTime=gpsData
                    self.current_epoch=1
                    if showoutput==1:
                        print(gpsTime)
                if gpsData[0]==alt_sentence:
                    #$GPGGA
                    gpsAlt = gpsData[9]
                    gpsUnit = gpsData[10]
                    self.altitude = gpsAlt+gpsUnit
                if gpsData[0]==sentence:
                    if gpsData[2]=='A':
                        gpsTime = gpsData[1]
                        #print(gpsTime)
                        gpsLat=float(gpsData[3])
                        gpsN=gpsData[4] 
                        gpsLon=float(gpsData[5])
                        gpsE=gpsData[6]

                        if (gpsN==south):
                            gpsLat = -gpsLat

                        latDeg = int(gpsLat/100)
                        latMin = gpsLat-latDeg*100
                        lat=latDeg+latMin/60

                        if (gpsE==west):
                            gpsLon = -gpsLon

                        lonDeg = int(gpsLon/100)
                        lonMin = gpsLon-lonDeg*100
                        lon=lonDeg+lonMin/60

                        self.mhGrid = mh.to_maiden(lat,lon,precision=self.location_precision)
                        #g=latlong2grid(lat,lon)
                        #self.current_ngr = str(g)
                        self.current_lat = lat
                        self.current_lon = lon
                        
                        #print('Location: %s, %s, %s, %s' % (lat,lon,self.mhGrid,g))
                        #self.setReadGPS(False)
                        #time.sleep(1)
                    #else:
                    #    print("GPS Active but no Fix")
                    #    print(gpsData)
        except (KeyboardInterrupt, SystemExit):
            self.setReadGPS(False)
            self.join()
            print("Done.\nClosing GPS Listener.")