Example #1
0
def write_last_message(mapfile, semaphore):
    last_message = {
        'author': author_process,
        'receiver': process_one_name,
        'action': LAST_MESSAGE
    }
    semaphore.acquire()
    utils.write_to_memory(mapfile, json.dumps(last_message))
    semaphore.release()
Example #2
0
def wait_for_new_message(initial_message, mapfile, semaphore):
    message_i_just_read = initial_message
    while message_i_just_read == initial_message:
        semaphore.acquire()
        message_i_just_read = utils.read_from_memory(mapfile)
        if not message_i_just_read == initial_message:
            utils.write_to_memory(mapfile, utils.READY_FOR_NEXT)
        semaphore.release()

        time.sleep(0.001)
    return message_i_just_read
Example #3
0
def main():
    utils.say("Oooo 'ello, I'm Mrs. Conclusion!")

    params = utils.read_params()

    semaphore = sysv_ipc.Semaphore(params["KEY"])
    memory = sysv_ipc.SharedMemory(params["KEY"])

    utils.say("memory attached at %d" % memory.address)

    what_i_wrote = ""
    s = ""

    for i in range(0, params["ITERATIONS"]):
        utils.say("i = %d" % i)
        if not params["LIVE_DANGEROUSLY"]:
            # Wait for Mrs. Premise to free up the semaphore.
            utils.say("acquiring the semaphore...")
            semaphore.acquire()

        s = utils.read_from_memory(memory)

        while s == what_i_wrote:
            if not params["LIVE_DANGEROUSLY"]:
                # Release the semaphore...
                utils.say("releasing the semaphore")
                semaphore.release()
                # ...and wait for it to become available again.
                utils.say("acquiring for the semaphore...")
                semaphore.acquire()

            s = utils.read_from_memory(memory)

        if what_i_wrote:
            if PY_MAJOR_VERSION > 2:
                what_i_wrote = what_i_wrote.encode()
            try:
                assert(s == hashlib.md5(what_i_wrote).hexdigest())
            except AssertionError:
                raise AssertionError("Shared memory corruption after %d iterations." % i)

        if PY_MAJOR_VERSION > 2:
            s = s.encode()
        what_i_wrote = hashlib.md5(s).hexdigest()

        utils.write_to_memory(memory, what_i_wrote)

        if not params["LIVE_DANGEROUSLY"]:
            utils.say("releasing the semaphore")
            semaphore.release()
        # TODO: remove
        time.sleep(1)
def gps_feeder(vehicle):
    write_header("GPS Feeder starting...")
    memory_gps = posix_ipc.SharedMemory("/GPS_SM",
                                        posix_ipc.O_CREAT,
                                        size=1024)
    mapfile_gps = mmap.mmap(memory_gps.fd, memory_gps.size)

    semaphore_gps = posix_ipc.Semaphore("/GPS_SEM", posix_ipc.O_CREAT)
    semaphore_gps.release()

    while True:
        try:
            time.sleep(0.2)

            if vehicle.gps_0.fix_type in (0, 1):
                write_warning("No GPS fix!")
                continue

            json_gps = {
                'time': time.time(),
                'lat': vehicle.location.global_frame.lat,
                'lon': vehicle.location.global_frame.lon,
                'alt': vehicle.location.global_frame.alt,
                'r_alt': vehicle.location.global_relative_frame.alt,
                'roll': vehicle.attitude.roll,
                'pitch': vehicle.attitude.pitch,
                'yaw': vehicle.attitude.yaw,
            }

            semaphore_gps.acquire(0.5)
            utils.write_to_memory(mapfile_gps, json.dumps(json_gps))
            semaphore_gps.release()

        except (KeyboardInterrupt, SystemExit):
            write_info_green("Ending...")
            semaphore_gps.release()
            mapfile_gps.close()
            memory_gps.close_fd()
            semaphore_gps.close()
            exit(0)

        except posix_ipc.BusyError:
            write_error("Busy error")

        except:
            write_error("Error")
            pass
Example #5
0
def create_shm_files():
    memory_gps = posix_ipc.SharedMemory("/GPS_SM",
                                        posix_ipc.O_CREAT,
                                        size=1024)
    mapfile_gps = mmap.mmap(memory_gps.fd, memory_gps.size)
    memory_cmd = posix_ipc.SharedMemory("/CMD_SM",
                                        posix_ipc.O_CREAT,
                                        size=1024)
    mapfile_cmd = mmap.mmap(memory_cmd.fd, memory_cmd.size)
    json_gps = {
        'time': 0,
        'lat': 0,
        'lon': 0,
        'alt': 0,
        'r_alt': 0,
        'roll': 0,
        'pitch': 0,
        'yaw': 0,
    }

    utils.write_to_memory(mapfile_gps, json.dumps(json_gps))
    mapfile_gps.close()
    memory_gps.close_fd()
    mapfile_cmd.close()
    memory_cmd.close_fd()

    gps_sem = posix_ipc.Semaphore("/GPS_SEM", posix_ipc.O_CREAT)
    cmd_sem = posix_ipc.Semaphore("/CMD_SEM", posix_ipc.O_CREAT)
    gps_sem.release()
    cmd_sem.release()
    gps_sem.close()
    cmd_sem.close()

    camera_queue = posix_ipc.MessageQueue("/CAMERA_Q", posix_ipc.O_CREAT)

    while True:
        try:
            tmp = camera_queue.receive(0.1)
        except:
            break

    camera_queue.close()
Example #6
0
def init_shm_semaphore():
    params = utils.read_params()

    # Create the shared memory and the semaphore.
    memory = posix_ipc.SharedMemory(params["SHARED_MEMORY_NAME"], posix_ipc.O_CREAT,
                                    size=params["SHM_SIZE"])
    semaphore = posix_ipc.Semaphore(params["SEMAPHORE_NAME"], posix_ipc.O_CREAT)

    # MMap the shared memory
    mapfile = mmap.mmap(memory.fd, memory.size)

    # Once I've mmapped the file descriptor, I can close it without
    # interfering with the mmap.
    memory.close_fd()

    # I seed the shared memory with a random string (the current time).
    what_i_wrote = time.asctime()
    utils.write_to_memory(mapfile, what_i_wrote)

    return semaphore, mapfile, what_i_wrote
Example #7
0
def wait_for_new_message2(reply_code, mapfile, semaphore, last_message=False):
    new_message_found = False
    while not new_message_found:
        semaphore.acquire()
        message_i_just_read = utils.read_from_memory(mapfile)
        json_i_just_read = json_to_obj(message_i_just_read)
        if json_i_just_read['author'] == process_one_name and json_i_just_read[
                'receiver'] == author_process:
            message_to_send = {
                'author': author_process,
                'receiver': process_one_name,
                'action': reply_code
            }
            # print ("got message:")
            # print json_i_just_read
            if last_message:
                message_to_send['action'] = LAST_MESSAGE
            utils.write_to_memory(mapfile, json.dumps(message_to_send))
            new_message_found = True
        semaphore.release()
        time.sleep(0.001)
    return json_i_just_read
Example #8
0
def main(semaphore, mapfile, what_i_wrote =""):
    vehicle = connection_uav()
    semaphore.release()
    semaphore.acquire()
    
    s = utils.read_from_memory(mapfile)
    print s

    # I keep checking the shared memory until something new has
    # been written.
    while s == what_i_wrote:
        # Nothing new; give Mrs. Conclusion another chance to respond.
        utils.say("Releasing the semaphore")
        semaphore.release()

        utils.say("Waiting to acquire the semaphore")
        semaphore.acquire()

        s = utils.read_from_memory(mapfile)

    what_i_wrote = vehicle.attitude
    utils.write_to_memory(mapfile, what_i_wrote)

    return what_i_wrote
    2,
    3
  ],
  "boolean": true,
  "color": "gold",
  "null": null,
  "number": 123,
  "object": {
    "a": "b",
    "c": "d"
  },
  "string": "Hello World"
}
"""

# Create the shared memory and the semaphore.
memory = posix_ipc.SharedMemory(params["SHARED_MEMORY_NAME"],
                                posix_ipc.O_CREX,
                                size=params["SHM_SIZE"])

# MMap the shared memory
mapfile = mmap.mmap(memory.fd, memory.size)

# Once I've mmapped the file descriptor, I can close it without
# interfering with the mmap.
memory.close_fd()

# I seed the shared memory with a random string (the current time).

utils.write_to_memory(mapfile, data)
Example #10
0
# and shared memory have separate key spaces, so one can safely use the 
# same key for each. This seems to be true in my experience.

# For purposes of simplicity, this demo code makes no allowance for the 
# failure of the semaphore or memory constructors. This is unrealistic 
# because one can never predict whether or not a given key will be available,
# so your code must *always* be prepared for these functions to fail. 

semaphore = sysv_ipc.Semaphore(params["KEY"], sysv_ipc.IPC_CREX)
memory = sysv_ipc.SharedMemory(params["KEY"], sysv_ipc.IPC_CREX)

# I seed the shared memory with a random value which is the current time.
what_i_wrote = time.asctime()
s = what_i_wrote

utils.write_to_memory(memory, what_i_wrote)

for i in range(0, params["ITERATIONS"]):
    utils.say("iteration %d" % i)
    if not params["LIVE_DANGEROUSLY"]:
        # Releasing the semaphore...
        utils.say("releasing the semaphore")
        semaphore.release()
        # ...and wait for it to become available again. In real code it'd be 
        # wise to sleep briefly before calling .acquire() in order to be 
        # polite and give other processes an opportunity to grab the semaphore
        # while it is free and thereby avoid starvation. But this code is meant
        # to be a stress test that maximizes the opportunity for shared memory
        # corruption, and politeness has no place in that.
        utils.say("acquiring the semaphore...")
        semaphore.acquire()
Example #11
0
            # ...and wait for it to become available again.
            utils.say("Waiting to acquire the semaphore")
            semaphore.acquire()

        s = utils.read_from_memory(mapfile)

    if what_i_wrote:
        if PY_MAJOR_VERSION > 2:
            what_i_wrote = what_i_wrote.encode()
        try:
            assert(s == hashlib.md5(what_i_wrote).hexdigest())
        except AssertionError:
            utils.raise_error(AssertionError, 
                              "Shared memory corruption after %d iterations." % i)

    if PY_MAJOR_VERSION > 2:
        s = s.encode()
    what_i_wrote = hashlib.md5(s).hexdigest()

    utils.write_to_memory(mapfile, what_i_wrote)
    
    if not params["LIVE_DANGEROUSLY"]:
        utils.say("Releasing the semaphore")
        semaphore.release()

semaphore.close()
mapfile.close()

utils.say("")
utils.say("%d iterations complete" % (i + 1))
Example #12
0
import time
import random
import json
import mmap
import sys
import hashlib
# 3rd party modules
import posix_ipc
# Utils for this demo
import utils

PY_MAJOR_VERSION = sys.version_info[0]
params = utils.read_params()
fake_content = {"name":"None" ,"type":"None" ,"distance": 43 ,"size": 12} 

# Create the shared memory and the semaphore.
memory = posix_ipc.SharedMemory(params["SHARED_MEMORY_NAME_DEPTH_CAMERA"], posix_ipc.O_CREAT,
                                size=params["SHM_SIZE"])
# MMap the shared memory
mapfile = mmap.mmap(memory.fd, memory.size)
# Once I've mmapped the file descriptor, I can close it without
# interfering with the mmap.
memory.close_fd()

while True:
    fake_distance = random.randint(0,120)
    fake_size = random.randint(0,120)
    fake_content['distance'] = fake_distance
    fake_content['size'] = fake_size
    utils.write_to_memory(mapfile, json.dumps(fake_content))#writing the data as a string at the shared memory location
    #time.sleep(1)
Example #13
0
# and shared memory have separate key spaces, so one can safely use the
# same key for each. This seems to be true in my experience.

# For purposes of simplicity, this demo code makes no allowance for the
# failure of the semaphore or memory constructors. This is unrealistic
# because one can never predict whether or not a given key will be available,
# so your code must *always* be prepared for these functions to fail.

semaphore = sysv_ipc.Semaphore(params["KEY"], sysv_ipc.IPC_CREX)
memory = sysv_ipc.SharedMemory(params["KEY"], sysv_ipc.IPC_CREX)

# I seed the shared memory with a random value which is the current time.
what_i_wrote = time.asctime()
s = what_i_wrote

utils.write_to_memory(memory, what_i_wrote)

for i in range(0, params["ITERATIONS"]):
    utils.say("iteration %d" % i)
    if not params["LIVE_DANGEROUSLY"]:
        # Releasing the semaphore...
        utils.say("releasing the semaphore")
        semaphore.release()
        # ...and wait for it to become available again. In real code it'd be
        # wise to sleep briefly before calling .acquire() in order to be
        # polite and give other processes an opportunity to grab the semaphore
        # while it is free and thereby avoid starvation. But this code is meant
        # to be a stress test that maximizes the opportunity for shared memory
        # corruption, and politeness has no place in that.
        utils.say("acquiring the semaphore...")
        semaphore.acquire()
Example #14
0
    blank_image = cv2.resize(blank_image,None,fx=(1/utils.SCALE_DOWN), fy=(1/utils.SCALE_DOWN), interpolation = cv2.INTER_CUBIC)
    return blank_image

if __name__ == '__main__':
    shared_memory, semaphore = access_shared_memory_and_semaphore()
    mapfile = mmap.mmap(shared_memory.fd, shared_memory.size)

    print("Starting the process")
    time.sleep(1)
    semaphore.acquire()
    first_readed_message = utils.read_from_memory(mapfile)
    if not first_readed_message == utils.FIRST_HANDSHAKE :
        print("brr, some bullshit here")
    else:
        print("Passing back the handshake")
    utils.write_to_memory(mapfile, utils.SECOND_HANDSHAKE)
    semaphore.release()
    message_i_just_read = utils.SECOND_HANDSHAKE
    # message_i_just_read = wait_for_new_message(message_i_just_read, mapfile, semaphore, False)
        


    while True:
        message_i_just_read = wait_for_new_message(message_i_just_read, mapfile, semaphore)
        if message_i_just_read == utils.THIRD_HANDSHAKE or message_i_just_read== utils.SECOND_HANDSHAKE:
            continue
        else:
            meta = json_to_obj(message_i_just_read)
            blank_image = draw_points_on_blank(meta)

            cv2.imshow('image',blank_image)
Example #15
0
# Once I've mmapped the file descriptor, I can close it without
# interfering with the mmap.
memory.close_fd()
# US sensor
us_sensor = {
    "US-distance": "None",
    "crashed": "False"
}  # the data that will be saved at the posix shared memory
crahed_dist = 5
sensor = DistanceSensor(
    echo=18,
    trigger=17)  # declaration of the sensor as a DistanceSensor object

while True:
    # print('Distance: ', sensor.distance * 100)
    us_sensor[
        "US-distance"] = sensor.distance * 100  # getting the distance in cm.

    if us_sensor[
            "US-distance"] <= crahed_dist:  # if the measured distace equal or less than the crahed_dist
        # than the "crahed" flag is raised
        us_sensor["crashed"] = True

    else:
        us_sensor["crashed"] = False

    utils.write_to_memory(
        mapfile, json.dumps(us_sensor)
    )  # writing the data as a string at the shared memory location
    # sleep(0.1)
Example #16
0
    try:
        shared_memory, semaphore = create_shared_memory_and_semaphore()

        mapfile = mmap.mmap(shared_memory.fd, shared_memory.size)
        shared_memory.close_fd()

        starting_message = {
            'author': author_process,
            'receiver': process_two_name,
            'action': utils.FIRST_HANDSHAKE
        }
        starting_message = json.dumps(starting_message)


        # starting_message = utils.FIRST_HANDSHAKE
        utils.write_to_memory(mapfile, starting_message)
        message_i_just_read = starting_message

        print("Waiting for second process")
        waiting_time = 0
        while message_i_just_read == starting_message:
            sys.stdout.write("\r{0}".format("."*waiting_time))
            sys.stdout.flush()
            semaphore.release()
            time.sleep(1)
            waiting_time+=1
            semaphore.acquire()
            message_i_just_read = utils.read_from_memory(mapfile)
        semaphore.release()

        print("")
Example #17
0
def write_last_message(mapfile, semaphore):
    semaphore.acquire()
    utils.write_to_memory(mapfile, utils.JOB_DONE)
    semaphore.release()    
Example #18
0
            utils.say("Waiting to acquire the semaphore")
            semaphore.acquire()

        s = utils.read_from_memory(mapfile)

    if what_i_wrote:
        if PY_MAJOR_VERSION > 2:
            what_i_wrote = what_i_wrote.encode()
        try:
            assert (s == hashlib.md5(what_i_wrote).hexdigest())
        except AssertionError:
            utils.raise_error(
                AssertionError,
                "Shared memory corruption after %d iterations." % i)

    if PY_MAJOR_VERSION > 2:
        s = s.encode()
    what_i_wrote = hashlib.md5(s).hexdigest()

    utils.write_to_memory(mapfile, what_i_wrote)

    if not params["LIVE_DANGEROUSLY"]:
        utils.say("Releasing the semaphore")
        semaphore.release()

semaphore.close()
mapfile.close()

utils.say("")
utils.say("%d iterations complete" % (i + 1))
Example #19
0
device = "\dev\ttyTHS2"
frame = gt.geotag(device)
print(type(frame))
py_major_version = sys.version_info[0]

print("Geotagging starts")
params = utils.read_params()

## Create the shared memory and the semaphore.
memory = posix_ipc.SharedMemory(params["SHARED_MEMORY_NAME"],
                                posix_ipc.O_CREX,
                                size=params["SHM_SIZE"])
semaphore = posix_ipc.Semaphore(params["SEMAPHORE_NAME"], posix_ipc.O_CREX,
                                0600, 1)

## MMap the shared memory
mapfile = mmap.mmap(memory.fd, memory.size)

## Once I've mmapped the file descriptor, I can close it without
## interfering with the mmap.
memory.close_fd()

print(semaphore.value)
semaphore.acquire()
print(frame.size, frame.mode)
image_to_be_written = frame.tobytes()
frame.show()
print(len(image_to_be_written))
utils.write_to_memory(mapfile, image_to_be_written)
semaphore.release()