Advertisement
Poganu

CarOS-Python

May 28th, 2022
1,148
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #########################################
  2. ########### Main.py function ############
  3. #########################################
  4.  
  5. #0. Import libraries
  6. #0. Define folder paths
  7. #0. Define functions
  8. #1. Read current time
  9. #2. Log engine start time
  10. #3. Create Reboot Counter folder
  11. #4. Check if Reboot Counter file present
  12. #5. Create Reboot Counter file initiated at value 0
  13. #6. Read reboot counter from text file
  14. #7. Check if reboot counter > 5
  15. #8. Send alert e-mail
  16. #9. Read Car-Database JSON file for truck specific info
  17. #10. Check if Queue Status JSON  file present for today
  18. #11. Create blank QueueStatus.json for today
  19. #12. Read QueueStatus.json file data
  20. #13. Check if CarOS/Files storage below 50%
  21. #14. Delete old folders from dev/sda/mnt/usb
  22. #15. Check if USB drive connected and readable
  23. #16. Try USB mount command
  24. #17. Check if USB mount succeeded
  25. #18. Move destination to MicroSD card
  26. #19. Check if available storage on USB Drive is below 30%
  27. #20. Delete the oldest daily folder with videos from /mnt/usb
  28. #21. Create daily folder for video storage on /mnt/usb or MicroSD
  29. #22. Capture video stream in daily folder
  30. #23. Search if video file present in folder
  31. #24. Check if waiting_counter greater than 3
  32. #25. Wait 30 sec
  33. #26. Increment waiting_counter
  34. #27. Check if most recent video is created more than 1 minute ago
  35. #28. Increment reboot counter
  36. #29. Reboot system
  37. #30. Search for 2nd most recent video in folder
  38. #31. Update upload queue with video and attributes
  39. #32. Check upload queue for videos with not-uploaded status
  40. #33. Wait 5s + looped-counter * 1.5
  41. #34. Looped-counter + 1
  42. #35. IF not-uploaded status
  43. #36. Grab last entry with status not-uploaded from queue
  44. #37. Analyse for covered camera
  45. #38. Analyse for dirt on camera
  46. #39. Analyse for empty cup
  47. #40. Split video into frames. Grab frame at 1/2 of video. Delete the other frames
  48. #41. Is GPS data server accessible?
  49. #42. Place static GPS location - car base location
  50. #43. Send e-mail alert
  51. #44. Get GPS data at video creation time
  52. #45. Upload file (video / frame)
  53. #46. Sent e-mail alert with frame attached + GPS data
  54.  
  55.  
  56. #---------------------------------------------------------------
  57. #0. Import libraries
  58. import json
  59. import glob
  60. import os
  61. import datetime
  62. import io
  63. from datetime import datetime
  64. from os.path import exists
  65. import pathlib
  66. import time
  67. import smtplib, ssl
  68. import subprocess as sp
  69. import requests
  70. import concurrent.futures
  71. import subprocess
  72.  
  73.  
  74. #---------------------------------------------------------------
  75. #0. Define folder paths
  76. #CarOS_folder_path = "/Users/cristianpogan/Desktop/Python-Scripts/RaspberryPi-Scripts/Test-New-Main/CarOS/"
  77. #All_videos_folder = "/Users/cristianpogan/Desktop/Python-Scripts/RaspberryPi-Scripts/Test-New-Main/mnt-usb/"
  78. #Car_Database_json = "/Users/cristianpogan/Desktop/Python-Scripts/Car-Database.json"
  79. CarOS_folder_path = "/home/pi/CarOS/"
  80. temp_video_path = "/home/pi/CarOS/Files/"
  81. All_videos_folder = "/mnt/usb/"
  82. Backup_videos_folder = "/home/pi/"
  83. E_mail_receiver = "pogancristian@gmail.com"
  84. Client_Name = "SOMA"
  85. Car_Name = "SB-37-SOM"
  86.  
  87. #---------------------------------------------------------------
  88. #0. Define functions
  89.  
  90. def split_stream_into_chunks():
  91.     #print("Arrived at split_stream_into_chunks")
  92.     ffmpeg_command = ["ffmpeg",
  93.             "-video_size", "1280x720",
  94.             "-framerate", "9",
  95.             "-f", "v4l2",
  96.             "-i", "/dev/video0",
  97.             "-f", "segment",
  98.             "-g", '1',
  99.             "-strftime", "1",
  100.             "-segment_time", "30",
  101.             "-segment_format", "mp4",
  102.             "-reset_timestamps", "1",
  103.             "-force_key_frames", "expr:gte(t,n_forced*30)", # set the number same as the segment length
  104.             image_filepath]
  105.  
  106.     #print("In split_stream_into_chunks")
  107.     subprocess.run(ffmpeg_command)
  108.  
  109. def Queue_management(upload_queue, upload_queue_location, upload_queue_json, \
  110.                     daily_folder_path, reboot_reasons_location, reboot_reasons_json, \
  111.                     Car_Database, E_mail_receiver, Car_Name):
  112.     #print("------Queue_management------")
  113.  
  114.     ##start = time.perf_counter()
  115.     ##print("Upload seqence start time: ", start)
  116.    
  117.     #print("--------------------22------------------------")
  118.     #print("#22. Initialize waiting counter at 0")
  119.    
  120.     waiting_counter = 0
  121.     #print("Resetted waiting_counter at 0")
  122.     waiting_counter2 = 0
  123.     #print("Resetted waiting_counter2 at 0")
  124.     loop_counter = 0
  125.  
  126.     informed_about_GPS_down = 0
  127.  
  128.     #Find most recent video in folder
  129.     taggedrootdir = pathlib.Path(daily_folder_path)
  130.  
  131.  
  132.     while True:
  133.  
  134.         #print("--------------------23------------------------")
  135.         #print("#23. Check if video file present in folder")
  136.  
  137.         try:
  138.             newest_video_full = max([f for f in taggedrootdir.resolve().glob('*.mp4') if f.is_file()], key=os.path.getctime)
  139.             #print("newest_video_full: ", newest_video_full)
  140.  
  141.             newest_video = str(newest_video_full).split(f"{daily_folder_path}",1)[1] #get only filename
  142.             #print("newest_video: ", newest_video)
  143.  
  144.  
  145.         except ValueError:
  146.             #print("folder empty - No video found - ffmpeg not started")
  147.  
  148.             #print("--------------------24------------------------")
  149.             #print("#24. Check if waiting_counter greater than 3")
  150.             if waiting_counter >= 3:
  151.                 #True
  152.                 reason = f"Waiting counter is {waiting_counter}"
  153.                 #print(reason)
  154.  
  155.                 Manage_lack_of_new_video(reboot_reasons_location, reboot_reasons_json, reason, E_mail_receiver)
  156.  
  157.             elif waiting_counter < 3:
  158.                 #False
  159.                 #print("--------------------25------------------------")
  160.                 #print("#25. Wait 30 sec, increment waiting_counter")
  161.                 time.sleep(30)
  162.  
  163.                 waiting_counter = waiting_counter + 1
  164.                 #print("Incremented waiting_counter: ", waiting_counter)
  165.  
  166.                 #print("--------------------26------------------------")
  167.                 #print("#26. Write to RebootReason.JSON, waited x for new video in folder y")
  168.  
  169.                 reason = f"waited {waiting_counter} times for new video in folder {daily_folder_path}"
  170.                 Write_to_reboot_reason(reboot_reasons_location, reboot_reasons_json, reason)
  171.            
  172.                 #print("--------------------27------------------------")
  173.                 #print("#27. Send e-mail alert with cause, car name and IP")
  174.                 Send_email_alert(E_mail_receiver, reason)
  175.  
  176.             else:
  177.                 #print("Error - waiting counter is not >= 3 and not < 3")
  178.                 #print(f"waiting counter value: {waiting_counter}")
  179.                 pass
  180.  
  181.  
  182.         #Video file found
  183.         #print("--------------------28------------------------")
  184.         #print("#28. Check if most recent video is created more than 1 minute ago")
  185.  
  186.         current = datetime.now()
  187.  
  188.         #Last time modified - taken from video filename
  189.         s1 = f"{str(newest_video)[-12:-10]}:{str(newest_video)[-9:-7]}:{str(newest_video)[-6:-4]}"
  190.         #newest_video_modified_hour, newest_video_modified_minute
  191.         #print("Current time: ", current.hour, current.minute, current.second)
  192.         #print("Latest video modified time: ", s1)
  193.  
  194.         #Compare modified time with current time
  195.         FMT = '%H:%M:%S'
  196.         tdelta = datetime.strptime(f"{current.hour}:{current.minute}:{current.second}", FMT) - datetime.strptime(s1, FMT)
  197.         #print("tdelta: ", tdelta, "\n")
  198.         tdelta_string = str(tdelta)
  199.         #print("tdelta_string: ", tdelta_string)
  200.  
  201.         #print("before cut")
  202.         #print("delta hours: |", tdelta_string[-8:-6], "|")
  203.         #print("delta minutes: |", tdelta_string[-5:-3], "|")
  204.         #print("delta seconds: |", tdelta_string[-2:], "|")
  205.    
  206.         delta_hours = int(tdelta_string[-8:-6]) #delta hours
  207.         delta_min = int(tdelta_string[-5:-3]) #delta minutes
  208.         delta_sec = int(tdelta_string[-2:]) #delta seconds
  209.  
  210.         #print("after cut")
  211.         #print("delta hours: ", delta_hours)
  212.         #print("delta minutes: ", delta_min)
  213.         #print("delta seconds: ", delta_sec)
  214.  
  215.         if delta_hours == 0 and delta_min < 1 and delta_sec <= 50:
  216.             #False - less than 50 seconds ago
  217.             #print("False - less than 50 seconds ago \n")
  218.  
  219.             #print("--------------------33------------------------")
  220.             #print("#33. Check if 2nd newest file present in video folder")
  221.  
  222.             videos_in_folder = sorted([f for f in taggedrootdir.resolve().glob('*.mp4') if f.is_file()], key=os.path.getctime)
  223.             if len(videos_in_folder) > 1:
  224.                 #True - present
  225.                 #print("More than 1 video file in folder.")
  226.                 #print(f"there are {len(videos_in_folder)} videos")
  227.  
  228.                 Manage_all_video_files(taggedrootdir, videos_in_folder, upload_queue_location, \
  229.                                     upload_queue_json, upload_queue, \
  230.                                     informed_about_GPS_down)
  231.  
  232.             else:
  233.                 #False - not present
  234.                 #print("--------------------34------------------------")
  235.                 #print("#34. Wait 30 sec - no alert needed")
  236.                 time.sleep(30)
  237.                
  238.         else:
  239.             #True
  240.             #True - more than 50 seconds ago
  241.  
  242.             reason = "True - more than 50 seconds ago"
  243.             #print(reason)
  244.  
  245.             Manage_lack_of_new_video(reboot_reasons_location, reboot_reasons_json, reason, E_mail_receiver)
  246.  
  247.  
  248.  
  249. def Manage_all_video_files(taggedrootdir, videos_in_folder, upload_queue_location, upload_queue_json, upload_queue, informed_about_GPS_down):
  250.  
  251.     #print("in Manage_all_video_files")
  252.  
  253.     #print("--------------------35------------------------")
  254.     #print("#35. Iterate from 2nd most recent to the oldest video")
  255.  
  256.     #print("all videos_in_folder")
  257.     #print(videos_in_folder)
  258.  
  259.     for num_of_vides in range(len(videos_in_folder) -1 ):
  260.        
  261.         #print("#In num_of_vides in range(len(videos_in_folder) -1 ) loop")
  262.        
  263.         #Must start from -1 even for 0 value of num_of_videos
  264.         video_index = (-2) - num_of_vides
  265.         #print("loop counter: ", num_of_vides)
  266.         #print("video index: ", video_index)
  267.         try:
  268.             video = str(sorted([f for f in taggedrootdir.resolve().glob('*.mp4') if f.is_file()], key=os.path.getctime)[video_index])
  269.         except Exception as ex:
  270.             template = "An exception of type {0} occurred. Arguments:\n{1!r}"
  271.             message = template.format(type(ex).__name__, ex.args)
  272.             #print("Error message: ", message)
  273.  
  274.         #print("video in full: ", video)
  275.         video = str(video[20:])
  276.         #print("video right part: ", video)
  277.  
  278.         #print("--------------------36------------------------")
  279.         #print("#36. Check if video in list is present in Upload Queue")
  280.  
  281.         if video in upload_queue:
  282.             #True - Present in list
  283.             #print(f"video {video} ")
  284.             #print(f"is in \n {upload_queue}")
  285.            
  286.             #print("--------------------38------------------------")
  287.             #print("#38. Check if video has status 1 uploaded")
  288.             if upload_queue[video]['uploaded_video'] == 1:
  289.                 #True - video has value 1 in queue - status uploaded
  290.                
  291.                 #print(video, " is present in Upload Queue")
  292.                 #print("Back to num_of_vides in range(len(videos_in_folder) -1 ) loop?")
  293.                 pass
  294.                
  295.            
  296.             elif upload_queue[video]['uploaded_video'] == 0:
  297.                 #False - video has value 0 in queue - status not-uploaded
  298.                 #print(video, " is NOT present in Upload Queue")
  299.                
  300.                 Process_video_file(video, upload_queue, informed_about_GPS_down)
  301.  
  302.             else:
  303.                 #print(f"Error reading status for video {video}")
  304.                 #Handle similar to exception cases
  305.                 pass
  306.  
  307.  
  308.         else:
  309.             #False - not present in list
  310.             #print(f"video {video} \nis NOT in \n{upload_queue}\n")
  311.  
  312.             #print("--------------------37------------------------")
  313.             #print("37. Place video in upload_queue with status 0")
  314.  
  315.             temp_dict = {
  316.             "uploaded_video": 0,
  317.             "uploaded_frame": 0,
  318.             "empty_cup": 0,
  319.             "dirt_on_camera": 0,
  320.             "covered_camera": 0
  321.             }
  322.  
  323.             #print("video: ", video)
  324.             #print("temp_dict: ", temp_dict)
  325.             #print(" ")
  326.             upload_queue[video] = temp_dict
  327.  
  328.                        
  329.             with open(f"{upload_queue_location}{upload_queue_json}", 'w') as f:
  330.                 json.dump(upload_queue, f, indent=2)
  331.            
  332.             Process_video_file(video, upload_queue, informed_about_GPS_down)
  333.  
  334.     #print("#Looped through all current files")
  335.     #print("Sleeping 20 sec")
  336.     time.sleep(20)
  337.  
  338.  
  339. def Process_video_file(video, upload_queue, informed_about_GPS_down):
  340.     #print("In Process_video_file")
  341.  
  342.     #print("--------------------34------------------------")
  343.     #print("#34. Analyse for covered camera")
  344.  
  345.     covered_camera_response = Covered_camera_check(upload_queue_location, upload_queue_json, upload_queue, video)
  346.     if covered_camera_response == 1:
  347.         #print(f"In {video} camera is not covered")
  348.         Split_video_into_frames(upload_queue_location, upload_queue_json, upload_queue, video, informed_about_GPS_down)
  349.     elif covered_camera_response == 0:
  350.         #print("Camera not covered")
  351.         pass # Move to 38. Analyse for dirt on camera
  352.     else:
  353.         #Place error in Errors.json
  354.         #print("Error")
  355.         error_message = str(f"ERROR at covered camera analysis.")
  356.         Write_to_reboot_reason(reboot_reasons_location, reboot_reasons_json, error_message)
  357.  
  358.     #print("--------------------35------------------------")
  359.     #print("#35. Analyse for dirt on camera")
  360.  
  361.     dirt_on_camera_response = Dirt_on_camera_check(upload_queue_location, upload_queue_json, upload_queue, video)
  362.     if dirt_on_camera_response == 1:
  363.         #print(f"In {video} camera there is no dirt on camera")
  364.         Split_video_into_frames(upload_queue_location, upload_queue_json, upload_queue, video, informed_about_GPS_down)
  365.     elif dirt_on_camera_response == 0:
  366.         #print("No dirt on camera")
  367.         pass # Move to 39. Analyse for empty cup
  368.     else:
  369.         #Place error in Errors.json
  370.         #print("Error")
  371.         error_message = str(f"ERROR at dirt on camera analysis.")
  372.         Write_to_reboot_reason(reboot_reasons_location, reboot_reasons_json, error_message)
  373.  
  374.     #print("--------------------36------------------------")
  375.     #print("#36. Analyse for empty cup")
  376.  
  377.     empty_cup_response = Empty_cup_check(upload_queue_location, upload_queue_json, upload_queue, video)
  378.     if empty_cup_response == 1:
  379.         #print(f"In {video} cup is full")
  380.         #print("Cup empty")
  381.         Split_video_into_frames(upload_queue_location, upload_queue_json, upload_queue, video, informed_about_GPS_down)
  382.     elif empty_cup_response == 0:
  383.         #print("Cup not empty")
  384.  
  385.         GPS_Data_Check(upload_queue_location, upload_queue_json, upload_queue, \
  386.                     daily_folder_path, video, Car_Database, informed_about_GPS_down, \
  387.                     E_mail_receiver, Car_Name)
  388.     else:
  389.         #Place error in Errors.json
  390.         #print("Error")
  391.         error_message = str(f"ERROR at empty cup analysis.")
  392.         #print("Error message: ", error_message)
  393.         Write_to_reboot_reason(reboot_reasons_location, reboot_reasons_json, error_message)
  394.  
  395.  
  396.  
  397. def Send_email_alert(receiver, message1):
  398.     sender_email = "PolyMore.Systems@gmail.com"
  399.     port = 465  #For SSL
  400.     password = "PolyMore1"
  401.     context = ssl.create_default_context()
  402.     message = f"Subject: Car {Car_Name} \n" + message1
  403.     #print("Sent e-mail")
  404.  
  405.     #Check if there is GSM signal for e-mail sending
  406.     try:
  407.         with smtplib.SMTP_SSL("smtp.gmail.com", port, context=context) as server:
  408.             server.login(sender_email, password)
  409.             server.sendmail(sender_email, receiver, message)
  410.     except Exception as ex:
  411.         error_message1 = " {0} occurred. Arguments:\n{1!r}".format(type(ex).__name__, ex.args)
  412.         error_message = str(f"ERROR Cannot send e-mail: {ex}. ") + error_message1
  413.         #print("Error message: ", error_message)
  414.  
  415.  
  416. def Write_to_reboot_reason(reboot_reasons_location, reboot_reasons_json, reason):
  417.  
  418.     if os.path.isfile(f"{reboot_reasons_location}{reboot_reasons_json}") and os.access(reboot_reasons_location, os.R_OK):
  419.         #print("Reboot Reason JSON file exists and is readable")
  420.  
  421.         try:
  422.             #Read current file
  423.             with open(f"{reboot_reasons_location}{reboot_reasons_json}") as json_file:
  424.                 reasons_dict = json.load(json_file)
  425.  
  426.             #Add reason to dict from file
  427.             time_stamp = f"{datetime.now().hour}-{datetime.now().minute}-{datetime.now().second}"
  428.             reasons_dict[time_stamp] = reason
  429.             #print("reasons_dict: ")
  430.             #print(reasons_dict)
  431.  
  432.             #Add updated reasons to JSON file
  433.             with io.open(os.path.join(reboot_reasons_location, reboot_reasons_json), 'w') as js_file:
  434.                 json.dump(reasons_dict, js_file)
  435.  
  436.             #Print for check
  437.             #print("Read reboot_reasons_json")
  438.             #print(reasons_dict)
  439.             #print("")
  440.  
  441.         except:
  442.             #print("JSON file cannot be read.")
  443.             with io.open(os.path.join(reboot_reasons_location, reboot_reasons_json), 'w') as js_file:
  444.                 js_file.write(json.dumps({})) #Write empty file
  445.  
  446.     else:
  447.         #print("File is missing or is not readable")
  448.        
  449.         #If reboot reasons JSON is not created, create it now
  450.         with io.open(os.path.join(reboot_reasons_location, reboot_reasons_json), 'w') as js_file:
  451.             js_file.write(json.dumps({})) #Write empty file
  452.         pass
  453.  
  454.  
  455. def Manage_lack_of_new_video(reboot_reasons_location, reboot_reasons_json, reason, E_mail_receiver):
  456.  
  457.     #print("--------------------29------------------------")
  458.     #print("#29.  Write to RebootReasons JSON file reason for reboot - no new video found")
  459.    
  460.     Write_to_reboot_reason(reboot_reasons_location, reboot_reasons_json, reason)   
  461.  
  462.     #print("--------------------30------------------------")
  463.     #print("#30. Send e-mail alert with cause for reboot")
  464.  
  465.     Send_email_alert(E_mail_receiver, reason)
  466.    
  467.     #print("--------------------31------------------------")
  468.     #print("#31. Wait 30 seconds - for log in at troubleshooting")
  469.     time.sleep(30)
  470.  
  471.     #print("--------------------32------------------------")
  472.     #print("#32. Wait 30 seconds - for log in at troubleshooting")
  473.  
  474.     os.system("sudo reboot")
  475.  
  476.  
  477. def Covered_camera_check(upload_queue_location, upload_queue_json, upload_queue, video):
  478.     #Do the check
  479.     #Return 1 if found
  480.     #Return 0 if not found
  481.     return 0
  482.  
  483. def Dirt_on_camera_check(upload_queue_location, upload_queue_json, upload_queue, video):
  484.     #Do the check
  485.     #Return 1 if found
  486.     #Return 0 if not found
  487.     return 0
  488.  
  489. def Empty_cup_check(upload_queue_location, upload_queue_json, upload_queue, video):
  490.     #Do the check
  491.     #Return 1 if found
  492.     #Return 0 if not found
  493.     return 0
  494.  
  495. def Split_video_into_frames(upload_queue_location, upload_queue_json, upload_queue, video, Car_Database, informed_about_GPS_down, E_mail_receiver):
  496.  
  497.     #print("--------------------37------------------------")
  498.     #print("#37. Split video into frames. Grab frame at 1/2 of video. Delete the other frames")
  499.  
  500.     GPS_Data_Check(upload_queue_location, upload_queue_json, upload_queue, daily_folder_path, video, Car_Database, informed_about_GPS_down, E_mail_receiver)
  501.     #return path and file generated after frame splitting
  502.  
  503. def Upload_file(upload_queue_location, upload_queue_json, upload_queue, daily_folder_path, video, Car_Database, lat, lng):
  504.  
  505.     #print("--------------------43------------------------")
  506.     #print("#43. Upload file (video / frame)")
  507.  
  508.     api_dashboard_post = 'http://api.polymore.ro/api/log'
  509.     #print(api_dashboard_post)
  510.  
  511.     #print("upload_queue:")
  512.     #print(upload_queue)
  513.     #print("")
  514.    
  515.     #print("video:")
  516.     #print(video)
  517.     #print("")
  518.  
  519.     #print("upload_queue[video]:")
  520.     #print(upload_queue[video])
  521.     #print("")
  522.  
  523.     #print("upload_queue[video]['uploaded_video']:")
  524.     #print(upload_queue[video]['uploaded_video'])
  525.     #print("")
  526.  
  527.     upload_queue[video]['uploaded_video'] = 1
  528.     #print("upload_queue[video]['uploaded_video']: ", upload_queue[video]['uploaded_video'])
  529.  
  530.     upload_queue[video]['uploaded_frame'] = -1
  531.     #print("upload_queue[video]['uploaded_frame']: ", upload_queue[video]['uploaded_frame'])
  532.  
  533.     #print("token: ", Car_Database['token'])
  534.    
  535.  
  536.     dashboard_token = Car_Database['token']
  537.     #print("----")
  538.  
  539.     #print(f"At location {upload_queue_location}")
  540.     #print(f"In queue {upload_queue}")
  541.     #print(f"Element {video} is being uploaded")
  542.  
  543.  
  544.     car_license_plate = Car_Name
  545.     file = daily_folder_path + video
  546.  
  547.     #In case there is no signal for video upload,
  548.     #don't interrupt the function from storing it locally
  549.     #print("before try in Upload_file")
  550.     try:
  551.         #print("in try in Upload_file")
  552.        
  553.         dashboard_request = requests.post(api_dashboard_post, headers = {
  554.             'x-auth-token': dashboard_token,
  555.         }, files = {
  556.                 'photos': open(file, 'rb')
  557.         }, data = {
  558.             'lat': lat,
  559.             'lng': lng,
  560.             'licensePlate': car_license_plate
  561.         })
  562.         #print(dashboard_request.text)
  563.  
  564.  
  565.         with io.open(os.path.join(upload_queue_location, upload_queue_json), 'w') as js_file:
  566.                 json.dump(upload_queue, js_file)
  567.        
  568.         #print(f"Uploaded {file}")
  569.  
  570.     except Exception as ex:
  571.         error_message1 = " {0} occurred. Arguments:\n{1!r}".format(type(ex).__name__, ex.args)
  572.         error_message = str(f"ERROR at Upload file: {ex}. ") + error_message1
  573.         #print("Error message: ", error_message)
  574.         Write_to_reboot_reason(reboot_reasons_location, reboot_reasons_json, error_message)
  575.  
  576.  
  577.        
  578. def Alert_with_frame(upload_queue_location, upload_queue_json, upload_queue, video, E_mail_receiver):
  579.  
  580.     #print("--------------------42------------------------")
  581.     #print("#42. Sent e-mail alert with frame attached + GPS data")
  582.     message1 = "Covered camera / Dirt on camera / Empty cup. "
  583.     Send_email_alert(E_mail_receiver, message1)
  584.     ##end = time.perf_counter()
  585.     ##print("end: ", end)
  586.     ##print(end - start)   
  587.     #Write to queue and JSON queue status update for video for which alert has been sent
  588.  
  589. def GPS_Data_Check(upload_queue_location, upload_queue_json, upload_queue, \
  590.                 daily_folder_path, video, Car_Database, \
  591.                 informed_about_GPS_down, E_mail_receiver, Car_Name):
  592.  
  593.     #print("Which video is received in GPS_Data_Check?")
  594.     #print("video: ", video)
  595.  
  596.     #print("in GPS data check")
  597.     api_safefleet_authenticate = 'https://delta.safefleet.eu/safefleet/api/authenticate_vehicle'
  598.     api_safefleet_vehicle_info = 'https://delta.safefleet.eu/safefleet/api/vehicles/'
  599.  
  600.     car_license_plate = Car_Name
  601.     #print("car_license_plate: ", car_license_plate)
  602.  
  603.     car_pin = Car_Database['pin']
  604.     #print("car_pin: ", car_pin)
  605.  
  606.     #print("--------------------38------------------------")
  607.     #print("#38. Check if authentication to GPS platform successful")
  608.  
  609.     try:
  610.         #True, platform accessible
  611.         authenticate = requests.post(api_safefleet_authenticate, \
  612.             headers = {'Content-Type': 'application/json'}, json = {
  613.             'license_plate': car_license_plate,
  614.             'pin': car_pin
  615.         })
  616.         #print(authenticate)
  617.         #print(authenticate.text)
  618.  
  619.  
  620.         #print("--------------------41------------------------")
  621.         #print("41. Get GPS data at video creation time")
  622.  
  623.         #GPS Presences
  624.         #Get_GPS_Presence(video)
  625.  
  626.  
  627.  
  628.         #This gets current lat, lng values
  629.  
  630.         vehicle_id = json.loads(authenticate.text)['vehicle']['vehicle_id']
  631.         vehicle_info = requests.get(api_safefleet_vehicle_info + str(vehicle_id), cookies=authenticate.cookies)
  632.         parsed_vehicle_info = json.loads(vehicle_info.text)
  633.  
  634.         lat = parsed_vehicle_info['current_info']['lat']
  635.         lng = parsed_vehicle_info['current_info']['lng']
  636.         #print(lat, lng)
  637.  
  638.        
  639.     except Exception as ex:
  640.         error_message1 = " {0} occurred. Arguments:\n{1!r}".format(type(ex).__name__, ex.args)
  641.         error_message = str(f"ERROR Safefleet platform not accesible: {ex}. ") + error_message1
  642.         #print("Error message: ", error_message)
  643.         Write_to_reboot_reason(reboot_reasons_location, reboot_reasons_json, error_message)
  644.  
  645.  
  646.         #False, platform inaccessible
  647.  
  648.         #Safefleet platform not accesible
  649.         #No GSM signal
  650.         #Place error in Error.json
  651.  
  652.         #print("--------------------39------------------------")
  653.         #print("#39. Place static GPS location - car base location")
  654.  
  655.         lat = Car_Database['base-GPS-lat']
  656.         lng = Car_Database['base-GPS-lng']
  657.  
  658.         #Put 00 / 00 if error
  659.  
  660.         #print("lat: ", lat)
  661.         #print("lng: ", lng)
  662.  
  663.         #print("--------------------40------------------------")
  664.         #print("#40. Send e-mail alert")
  665.         #Send the e-mail only once. Have a variable informed_about_GPS_down = 0
  666.         #This stops the function to alert at every 30 seconds
  667.  
  668.         if informed_about_GPS_down == 0:
  669.             message1 = "GPS Data not accesible. "
  670.             Send_email_alert(E_mail_receiver, message1)
  671.             #print("Sent e-mail. informed_about_GPS_down = 1")
  672.             informed_about_GPS_down = 1
  673.  
  674.     Upload_file(upload_queue_location, upload_queue_json, upload_queue, daily_folder_path, video, Car_Database, lat, lng)
  675.  
  676.     #Alert_with_frame()
  677.     #Boolean parameter in GPS_Data_Check for upload_frame and another one for upload_video
  678.     #For choosing which function to call here Upload_file / Send e-mail alert with attached frame
  679.  
  680.     return informed_about_GPS_down
  681.  
  682.  
  683. def Get_GPS_Presence(file):
  684.  
  685.     #print("# Authentificate in Safefleet platform")
  686.     api_safefleet_authenticate_platform = 'https://delta.safefleet.eu/safefleet/api/authenticate'
  687.     authenticate = requests.post(api_safefleet_authenticate_platform, \
  688.                    headers = {'Content-Type': 'application/json'}, \
  689.                    json = {'username': "polymore", 'password': "123456"})
  690.     #print(f"authenticate: {authenticate}")
  691.     #print(f"authenticate.text: {authenticate.text}")
  692.  
  693.     #5. Get every video in folder
  694.     #print(f'{file}')
  695.  
  696.     #6. Find start_moment and stop_moment
  697.     v_year = file[-17:-13]
  698.     v_month = file[-20:-18]
  699.     v_day = file[-23:-21]
  700.     v_hour = file[-12:-10]
  701.     v_minute = file[-9:-7]
  702.     v_second = file[-6:-4]
  703.    
  704.     #print(f'v_year: {v_year}')
  705.     #print(f'v_month: {v_month}')
  706.     #print(f'v_day: {v_day}')
  707.     #print(f'v_hour: {v_hour}')
  708.     #print(f'v_minute: {v_minute}')
  709.     #print(f'v_second: {v_second}')
  710.  
  711.     stop_moment = f"{v_year}-{v_month}-{v_day}T{v_hour}:{v_minute}:{v_second}Z"
  712.     #print(f'stop_moment: {stop_moment}')
  713.  
  714.     #If subtracting a delay minute that is under 1, subtract 1 hour, subtract 59 - delay
  715.     if int(v_minute) - delay_start_stop_moment <= 1:
  716.         #subtract 1 hour
  717.         v_temp = int(v_hour) - 1
  718.        
  719.         if int(v_hour) < 10:
  720.             #if hour smaller than 10, insert 0 as first character
  721.             v_hour = str("0" + str(v_temp))
  722.             #print("Hour smaller than 10: ", v_hour)
  723.        
  724.         else:
  725.             #else only subtract 1
  726.             v_hour = str(v_temp)
  727.             #print("Hour larger than 10: ", v_hour)
  728.         #subtract 59 - delay
  729.         v_minute = 59 - (delay_start_stop_moment - 1)
  730.  
  731.    
  732.     elif int(v_minute) - delay_start_stop_moment > 1:
  733.         #else, only subtract delay from current minute, keep same hour
  734.         #keep hour
  735.         #subtract delay
  736.         v_temp = int(v_minute) - delay_start_stop_moment
  737.  
  738.         if int(v_temp) < 10:
  739.             #if new minute is smaller than 10, insert 0 as first character
  740.             #print("Start minute is smaller than 10: ", v_minute)
  741.             v_minute = str("0" + str(v_temp))
  742.             #print("Adjusted characters: ", v_minute)
  743.  
  744.         else:
  745.             #else only subtract delay
  746.             #print("Start minute larger than 10: ", v_minute)
  747.             v_minute = str(v_temp)
  748.             #print("Subtracted: ", v_minute)
  749.  
  750.     else:
  751.         #print("Error")
  752.         #else, Error
  753.         pass
  754.  
  755.  
  756.     start_moment = f"{v_year}-{v_month}-{v_day}T{v_hour}:{v_minute}:{v_second}Z"
  757.    
  758.     #print("--------")
  759.     #print(f'start_moment: {start_moment}')
  760.     #print(f'stop_moment:  {stop_moment}')
  761.     #print("--------")
  762.    
  763.     api_safefleet_presences = f"https://delta.safefleet.eu/safefleet/api/vehicles/{vehicle_id}/presences/?start_moment={start_moment}&stop_moment={stop_moment}"#&filter_dist_percent={filter_dist_percent}"
  764.     #print(api_safefleet_presences)
  765.    
  766.     #try - if query not ok
  767.     presences1 = requests.get(api_safefleet_presences, cookies = authenticate.cookies)
  768.     #print(type(presences1))
  769.     #print((presences1))
  770.     presences = json.loads(presences1.text)
  771.     #print("Presences: ", presences)
  772.     if len(presences) == 0:
  773.         count_missing = count_missing + 1
  774.         #print("count_missing: ", count_missing)
  775.  
  776.  
  777.         #Return lat, lng for car-base
  778.  
  779.  
  780.     else:
  781.  
  782.         #Presences return is not empty
  783.         #Compare all returned presences in response
  784.  
  785.         #4. Check in presences the closest presence to the video name
  786.         for x in range(len(presences)):
  787.        
  788.             a = presences[x]
  789.             #print(a)
  790.  
  791.             b = a['moment']
  792.             #print(b)
  793.  
  794.             pres_day = b[8:10]
  795.             pres_hour = b[-9:-7]
  796.             pres_min = b[-6:-4]
  797.             pres_sec = b[-3:-1]
  798.  
  799.             #print(f"pres_day: {pres_day}")
  800.             #print(f"pres_hour: {pres_hour}")
  801.             #print(f"pres_min: {pres_min}")
  802.             #print(f"pres_sec: {pres_sec}")
  803.  
  804.             #for element in presences
  805.             s1 = f"{v_hour}:{v_minute}:{v_second}"
  806.             s2 = f"{pres_hour}:{pres_min}:{pres_sec}"
  807.            
  808.             #Compare modified time with current time
  809.             FMT = '%H:%M:%S'
  810.             tdelta = datetime.strptime(s1, FMT) - datetime.strptime(s2, FMT)
  811.             #print("tdelta: ", tdelta, "\n")
  812.             tdelta_string = str(tdelta)
  813.             #print("tdelta_string: ", tdelta_string)
  814.  
  815.  
  816.             #in case one of the values cannot be converted to int
  817.             try:
  818.                 delta_hours = int(tdelta_string[-8:-6]) #delta hours
  819.                 delta_min = int(tdelta_string[-5:-3]) #delta minutes
  820.                 delta_sec = int(tdelta_string[-2:]) #delta seconds
  821.             except:
  822.                 # Reset to 0, to wait for different current.second - to be different than 0
  823.                 #print("Except tdelta")
  824.                 pass
  825.  
  826.             #print("delta hours: ", delta_hours)
  827.             #print("delta minutes: ", delta_min)
  828.             #print("delta seconds: ", delta_sec)
  829.  
  830.             if delta_hours == 0 and delta_min < 1 and delta_sec <= 30:
  831.                 #print("yes")
  832.                 #print(a['lat'])
  833.                 #print(a['lng'])
  834.                 pass
  835.  
  836.     #if presences1.status_code != 200:
  837.     #   sys.exit()
  838.     #print(" ")
  839.  
  840.     #print("Len presences: ", len(presences))
  841.     #print(presences[1]['moment'])
  842.     #print(type(presences))
  843.     #print(" ")
  844.  
  845.    
  846.  
  847. print("--------------------1------------------------")
  848. print("#1. Read current date")
  849.  
  850. #Add a 0 to day if lower than 10 - to have 2 characters consistently
  851. current_day = datetime.now().day
  852. current_day = "0" + str(current_day) if current_day < 10 else str(datetime.now().day)
  853. print(current_day)
  854.  
  855. #Add a 0 to month if lower than 10 - to have 2 characters consistently
  856. current_month = datetime.now().month
  857. current_month = "0" + str(current_month) if current_month < 10 else str(datetime.now().month)
  858. print(current_month)
  859.  
  860. current_year = str(datetime.now().year)
  861. print(current_year)
  862.  
  863.  
  864. #print("--------------------2------------------------")
  865.  
  866. dt_split(datetime.datetime.now())
  867.  
  868. def str_from_dt(dt, fmt='%Y-%m-%d %H:%M:%S.%f'):
  869.     return dt.strftime(fmt)
  870.  
  871.  
  872. def dt_from_str(dt, fmt='%Y-%m-%d %H:%M:%S.%f'):
  873.     return datetime.datetime.strptime(dt, fmt)
  874.  
  875.  
  876. def is_datetime(x): return isinstance(x, (datetime.datetime, datetime.date, datetime.time))
  877.  
  878. def dt_split(dt):
  879.     if is_datetime(dt):
  880.         dt = str_from_dt(dt)
  881.  
  882.     date, time = dt.split(' ')
  883.     year, month, day = date.split('-')
  884.     h, m, s, milli = time.replace('.', ':').split(':')
  885.     return (year, month, day), (h, m, s, milli)
  886.  
  887.  
  888. #print("--------------------2------------------------")
  889. #print("#2. Send e-mail info - new engine start time")
  890.  
  891. engine_start_time = f"Engine ON at: {current_year}-{current_month}-{current_day}-{datetime.now().hour}-{datetime.now().minute}-{datetime.now().second}"
  892. test_message = "Engine Started"
  893. Send_email_alert(E_mail_receiver, test_message)
  894. #print(engine_start_time)
  895.  
  896. #print("--------------------3------------------------")
  897. #print("#3. Create RebootReasons folder")
  898.  
  899. reboot_reasons_location = CarOS_folder_path + "RebootReasons/" #CarOS/RebootReasons/
  900. os.system(f"mkdir {reboot_reasons_location}")
  901.  
  902. #print("--------------------4------------------------")
  903. #print("#4. Check if Reboot-Reason-daily.json file present")
  904.  
  905. reboot_reasons_json = "RebootReasons-" + datetime.now().strftime("%d-%m-%Y") + ".json"
  906. reboot_reasons = {}
  907. #print(f"{reboot_reasons_location}{reboot_reasons_json}")
  908.  
  909. if os.path.isfile(f"{reboot_reasons_location}{reboot_reasons_json}") and os.access(reboot_reasons_location, os.R_OK):
  910.     #Present
  911.     #print("File exists and is readable")
  912.  
  913.     #print("--------------------6------------------------")
  914.     #print("#6. Read RebootReason.json file data")
  915.  
  916.     try:
  917.         with open(f"{reboot_reasons_location}{reboot_reasons_json}") as json_file:
  918.             reboot_reasons = json.load(json_file)
  919.     except:
  920.         #print("JSON file cannot be read.")
  921.         with io.open(os.path.join(reboot_reasons_location, reboot_reasons_json), 'w') as js_file:
  922.             js_file.write(json.dumps({})) #Write empty file
  923.  
  924.     #print("Read reboot_reasons_json")
  925.     #print(reboot_reasons)
  926.     #print("")
  927.  
  928. else:
  929.     #RebootReason.json is missing or is not readable, creating file
  930.     #print("RebootReason.json is missing or is not readable, creating file")
  931.    
  932.     #print("--------------------5------------------------")
  933.     #print("#5. Create blank RebootReason-daily.json for today")
  934.     with io.open(os.path.join(reboot_reasons_location, reboot_reasons_json), 'w') as js_file:
  935.         js_file.write(json.dumps({})) #Write empty file
  936.  
  937. #print(reboot_reasons)
  938.  
  939. #print("--------------------7------------------------")
  940. #print("#7. Check if Car-Database JSON file for truck data is present and readable")
  941. Car_Database_json = CarOS_folder_path + "Car-Database.json"
  942.  
  943. try:
  944.     #Present - if entire block is executed
  945.     #print("--------------------9------------------------")
  946.     #print("#9. Read Car-Dabase.json for specific truck data")
  947.  
  948.     with open(Car_Database_json) as json_file:
  949.         Car_Database1 = json.load(json_file)
  950.     Car_Database = Car_Database1['client'][Client_Name][Car_Name]
  951.     #print("Car_Database: ")
  952.     #print(Car_Database)
  953.  
  954.  
  955. except FileNotFoundError as ex:
  956.     error_message1 = " {0} occurred. Arguments:\n{1!r}".format(type(ex).__name__, ex.args)
  957.     error_message = str(f"ERROR Car_Database file not present!: {ex}. ") + error_message1
  958.     #print("Error message: ", error_message)
  959.     Write_to_reboot_reason(reboot_reasons_location, reboot_reasons_json, error_message)
  960.  
  961.     #print("--------------------8------------------------")
  962.     #print("8. Send e-mail alert for JSON file presence")
  963.  
  964.     #If CarDatabase JSON file not found, send e-mail
  965.     message =  f"Car_Database file not present!"
  966.     Send_email_alert(E_mail_receiver, message)
  967.  
  968.  
  969.  
  970.  
  971. #print("--------------------10------------------------")
  972. #print("#10. Check if Queue Status JSON file present for today")
  973.  
  974. upload_queue_location = CarOS_folder_path + "Upload-Queues/" #CarOS/Upload-Queues/
  975. upload_queue_json = "Upload_queue-" + datetime.now().strftime("%d-%m-%Y") + ".json"
  976. upload_queue = {}
  977. #print(f"{upload_queue_location}{upload_queue_json}")
  978.  
  979. if os.path.isfile(f"{upload_queue_location}{upload_queue_json}") and os.access(upload_queue_location, os.R_OK):
  980.     #Present
  981.  
  982.     #print("--------------------12------------------------")
  983.     #print("#12. Read QueueStatus.json file data")
  984.  
  985.     #print("File exists and is readable")
  986.  
  987.     try:
  988.         with open(f"{upload_queue_location}{upload_queue_json}") as json_file:
  989.             upload_queue = json.load(json_file)
  990.     except:
  991.         #print("JSON file cannot be read.")
  992.         with io.open(os.path.join(upload_queue_location, upload_queue_json), 'w') as js_file:
  993.             js_file.write(json.dumps({})) #Write empty file
  994.  
  995.     #print("Read upload_queue")
  996.     #print(upload_queue)
  997.     #print("")
  998.  
  999. else:
  1000.     #Not Present
  1001.     #print("--------------------11------------------------")
  1002.     #print("#11. Create blank QueueStatus.json for today")
  1003.    
  1004.     #If foder with upload queues is not created, create it now
  1005.     os.system(f"mkdir {upload_queue_location}")
  1006.     #print("File is missing or is not readable, creating file")
  1007.    
  1008.     #If upload queue is not created, create it now
  1009.     with io.open(os.path.join(upload_queue_location, upload_queue_json), 'w') as js_file:
  1010.         js_file.write(json.dumps({})) #Write empty file
  1011.  
  1012.     #print("Created upload_queue")
  1013.     #print(upload_queue)
  1014.     #print("")
  1015.  
  1016. #print("--------------------13------------------------")
  1017. #print("#13. Check if CarOS.log file larger than 500 MB")
  1018.  
  1019. carOS_log_file = '/home/pi/CarOS.log'
  1020. carOS_log_size = os.path.getsize(carOS_log_file)
  1021. #print(carOS_log_size)
  1022. #print(type(carOS_log_size))
  1023.  
  1024. #Compare CarOS.log size to 500 MB
  1025. if carOS_log_size >= 500000000:
  1026.     #True - file larger than 500Mb
  1027.     #print("CarOS.log greater than 500 Mb")
  1028.  
  1029.     #print("--------------------14------------------------")
  1030.     #print("#14. Send e-mail info for CarOS.log file too large")
  1031.     message =  f"CarOS.log file greater than 500 MB. {carOS_log_size} MB!"
  1032.     Send_email_alert(E_mail_receiver, message)
  1033.  
  1034. else:
  1035.     #False - file smaller than 500Mb
  1036.     #print("Smaller")
  1037.     pass
  1038.  
  1039.  
  1040. #print("--------------------15------------------------")
  1041. #print("#15. Check if /mnt/usb  storage can be read")
  1042.  
  1043. Disk_space2 = sp.getoutput('df -h')
  1044. #print("Disk_space2: ", Disk_space2)
  1045.  
  1046. try:
  1047.     #True /mnt/usb storage can be read
  1048.     Disk_space1 = Disk_space2.rpartition('/mnt/usb')[0][-6:-2]
  1049.     Disk_space = [int(s) for s in Disk_space1.split() if s.isdigit()]
  1050.  
  1051.     #print("/mnt/usb: |", Disk_space[0], "|")
  1052.     #print(type(Disk_space[0]))
  1053.  
  1054.     #print("--------------------18------------------------")
  1055.     #print("#18. Check if /mnt/usb storage occupancy above 70%")
  1056.     for x in range(0,3):
  1057.         try:
  1058.             if int(Disk_space[0]) >= 70:
  1059.                 #print("Disk full: ", Disk_space)
  1060.                
  1061.                 #print("--------------------19------------------------")
  1062.                 #print("#19. Delete oldest folder from mnt/usb")
  1063.                
  1064.                 try:
  1065.                     oldest_video_folder = sorted(glob.glob(os.path.join(All_videos_folder, '*/')), key=os.path.getmtime)[-1]
  1066.                     #print(f"Removing {oldest_video_folder}")
  1067.                     os.system(f"rm -r {oldest_video_folder}/")
  1068.                 except Exception as ex:#IndexError:
  1069.                     #print("No folder found")
  1070.                     error_message1 = " {0} occurred. Arguments:\n{1!r}".format(type(ex).__name__, ex.args)
  1071.                     error_message = str(f"ERROR Cannot delete from /mnt/usb: {ex}. ") + error_message1
  1072.                     #print("Error message: ", error_message)
  1073.                     Write_to_reboot_reason(reboot_reasons_location, reboot_reasons_json, error_message)
  1074.                     pass
  1075.                
  1076.         except Exception as ex: #TypeError:
  1077.             error_message1 = " {0} occurred. Arguments:\n{1!r}".format(type(ex).__name__, ex.args)
  1078.             error_message = str(f"ERROR Cannot compare /mnt/usb value to 70: {ex}. ") + error_message1
  1079.             #print("Error message: ", error_message)
  1080.             #Write_to_reboot_reason(reboot_reasons_location, reboot_reasons_json, error_message)
  1081.        
  1082. except Exception as ex:
  1083.     template = "An exception of type {0} occurred. Arguments:\n{1!r}"
  1084.     message = template.format(type(ex).__name__, ex.args)
  1085.  
  1086.     Write_to_reboot_reason(reboot_reasons_location, reboot_reasons_json, message)
  1087.     #print("Error message: ", message)
  1088.     #print(f"ERROR : {ex}")
  1089.     #False - cannot be read
  1090.  
  1091.     #print("--------------------16------------------------")
  1092.     #print("#16. Check if storage occupancy on /dev/root < 70%")
  1093.    
  1094.     try:
  1095.         #In case issue arrises also with /dev/root reading
  1096.         result = Disk_space2.split("/dev/root",1)[1] #grab all text after "/dev/root"
  1097.         index = result.find("%") #find first occurance of "%"
  1098.  
  1099.         result1 = result[:index] #cut and grab only first part of string, before "%"
  1100.         OS_space = int(result1[-3:])
  1101.  
  1102.         #print("OS_space: ", OS_space)
  1103.  
  1104.         for x in range(0,3):
  1105.             try:
  1106.                 if OS_space >= 70:
  1107.                     #print("/dev/root full: ", OS_space)
  1108.                    
  1109.                     #print("--------------------17------------------------")
  1110.                     #print("#17. Delete oldest folder from dev/sda/mnt/usb")
  1111.                    
  1112.                     try:
  1113.                         oldest_video_folder = sorted(glob.glob(os.path.join(All_videos_folder, '*/')), key=os.path.getmtime)[-1]
  1114.                         #print(f"Removing {oldest_video_folder}")
  1115.                         os.system(f"rm -r {oldest_video_folder}/")
  1116.  
  1117.                     except Exception as ex: #IndexError:
  1118.                         #print("No folder found")
  1119.                         error_message1 = " {0} occurred. Arguments:\n{1!r}".format(type(ex).__name__, ex.args)
  1120.                         error_message = str(f"ERROR Cannot delete from /dev/sda: {ex}. ") + error_message1
  1121.                         #print("Error message: ", error_message)
  1122.                         Write_to_reboot_reason(reboot_reasons_location, reboot_reasons_json, error_message)
  1123.                        
  1124.                 else:
  1125.                     #print("Enough space available")
  1126.                     pass
  1127.                    
  1128.             except Exception as ex:#TypeError:
  1129.                 error_message1 = " {0} occurred. Arguments:\n{1!r}".format(type(ex).__name__, ex.args)
  1130.                 error_message = str(f"ERROR Cannot compare /root/dev/ value to 70: {ex}. ") + error_message1
  1131.                 #print("Error message: ", error_message)
  1132.                 Write_to_reboot_reason(reboot_reasons_location, reboot_reasons_json, error_message)
  1133.  
  1134.                 message =  f"Cannot compare /root/dev/ value to 70"
  1135.                 Send_email_alert(E_mail_receiver, message)
  1136.                 #print("Sent e-mail alert: Cannot compare /root/dev/ value to 70.")
  1137.                
  1138.                
  1139.     except Exception as ex:
  1140.         error_message1 = " {0} occurred. Arguments:\n{1!r}".format(type(ex).__name__, ex.args)
  1141.         error_message = str(f"ERROR -16-: {ex}. ") + error_message1
  1142.         #print("Error message: ", error_message)
  1143.         Write_to_reboot_reason(reboot_reasons_location, reboot_reasons_json, error_message)
  1144.        
  1145.  
  1146. #print("--------------------20------------------------")
  1147. #print("#20. Create daily folder for video storage on /mnt/usb")
  1148.  
  1149. daily_folder_name = str(current_day) + "-" + str(current_month) + "-" + str(current_year) + "/"
  1150. #print(daily_folder_name)
  1151.  
  1152. daily_folder_path = f"{All_videos_folder}{daily_folder_name}"
  1153. #Make daily folder for videos
  1154. os.system(f"sudo mkdir {daily_folder_path}")
  1155. os.system(f"sudo chmod 777 {daily_folder_path}")
  1156.  
  1157. #print("--------------------21------------------------")
  1158. #print("#21. Capture video stream in daily folder")
  1159.  
  1160. current = datetime.now()
  1161. current_hour = current.hour
  1162. if current_hour < 10:
  1163.     current_hour = "0" + str(current_hour)
  1164.  
  1165. current_minute = current.minute
  1166. if current_minute < 10:
  1167.     current_minute = "0" + str(current_minute)
  1168.  
  1169. current_second = current.second
  1170. if current_second < 10:
  1171.     current_second = "0" + str(current_second)
  1172.  
  1173. image_filepath = f"{daily_folder_path}{Car_Name}-%d-%m-%Y-%H-%M-%S.mp4"
  1174. #print("image_filepath: ", image_filepath)
  1175.  
  1176.  
  1177. with concurrent.futures.ProcessPoolExecutor() as executor:
  1178.     f1 = executor.submit(split_stream_into_chunks)
  1179.  
  1180.     #print("PRINT5: Sleeping 5 sec\n")
  1181.     time.sleep(5)
  1182.     #print("PRINT6: Slept for 5 sec\n")
  1183.  
  1184.     f2 = executor.submit(Queue_management, upload_queue, upload_queue_location, \
  1185.                         upload_queue_json, daily_folder_path, reboot_reasons_location, \
  1186.                         reboot_reasons_json, Car_Database, E_mail_receiver, Car_Name)
  1187.  
  1188.  
Advertisement
RAW Paste Data Copied
Advertisement