{"id":9743,"date":"2024-01-10T19:38:30","date_gmt":"2024-01-10T19:38:30","guid":{"rendered":"https:\/\/max-drake.cc\/?p=9743"},"modified":"2024-01-10T19:38:30","modified_gmt":"2024-01-10T19:38:30","slug":"sending-data-over-wifi-from-raspberry-pi-pico-w-to-local-pc","status":"publish","type":"post","link":"https:\/\/max-drake.cc\/?p=9743","title":{"rendered":"Sending data over wifi from Raspberry Pi Pico W to local PC"},"content":{"rendered":"<p>I sent data from Raspberry Pi Pico W over wifi to local PC.<\/p>\n<p><img decoding=\"async\" class=\"alignnone size-full wp-image-9727 lazyload\" data-src=\"http:\/\/max-drake.cc\/wp-content\/uploads\/2024\/01\/IMG20240103170203.png\" alt=\"\" width=\"640\" height=\"480\" src=\"data:image\/svg+xml;base64,PHN2ZyB3aWR0aD0iMSIgaGVpZ2h0PSIxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjwvc3ZnPg==\" style=\"--smush-placeholder-width: 640px; --smush-placeholder-aspect-ratio: 640\/480;\" \/><\/p>\n<h3>1. Start listener program on PC and then program on Pico<\/h3>\n<ol>\n<li>local PC script must be running first, as its listening for the data to come in on all IP addresses but on a specific port<\/li>\n<li>Fire up the pico code to send data to the local PC<\/li>\n<\/ol>\n<h3>2. Send data with identifiers as to which Pico sending, as all data goes to same file (at this time)<\/h3>\n<p>I want to develop to be able to have multiple Raspberry Pi Pico W&#8217;s send data to local PC, on same port , but it needs to differentiate between them- it can do this:<br \/>\nFirstly- by IP address on wifi<br \/>\nSecondly -We need to be able to send the PicoID across as well, so we know which device data is coming form<br \/>\nTurdly, we need to stream relevant data\u00a0 from Sensor, as well as correct datetime to local PC<\/p>\n<h3><strong>3. Local PC has to manage the data &#8211; we will write it to a single .txt file<\/strong><br \/>\nFirst step, write it all to a file<br \/>\nso far, have been able to write &#8211; IP address and DateTime to a file<\/h3>\n<pre><code class=\"language-ad-example\">('192.168.1.5', 57865),b'DateTime: 2024-01-10 9:08:07'\r\n('192.168.1.5', 57866),b'DateTime: 2024-01-10 9:08:11'\r\n('192.168.1.5', 57867),b'DateTime: 2024-01-10 9:08:15'\r\n('192.168.1.5', 57868),b'DateTime: 2024-01-10 9:08:19'\r\n('192.168.1.5', 57869),b'DateTime: 2024-01-10 9:08:23'\r\n('192.168.1.5', 57870),b'DateTime: 2024-01-10 9:08:27'\r\n<\/code><\/pre>\n<p>can be modified to<\/p>\n<pre><code class=\"language-ad-example\">('192.168.1.5', 57896),b'Pico2,DateTime: 2024-01-10 9:36:56'\r\n('192.168.1.5', 57897),b'Pico2,DateTime: 2024-01-10 9:37:00'\r\n('192.168.1.5', 57898),b'Pico2,DateTime: 2024-01-10 9:37:04'\r\n('192.168.1.5', 57899),b'Pico2,DateTime: 2024-01-10 9:37:08'\r\n('192.168.1.5', 57900),b'Pico2,DateTime: 2024-01-10 9:37:12'\r\n<\/code><\/pre>\n<h4>So code for Raspberry Pi Pico W:<\/h4>\n<pre><code class=\"language-Python\"># GetTimePico2LocalPC_v2.py\r\n\r\nimport socket\r\nimport network\r\nimport time\r\n# from time import strftime, localtimeimport os\r\nimport ntptime\r\nimport os\r\nfrom machine import Pin, RTC\r\n\r\n# Set variables\r\nPicoID='Pico2'\r\nip4LocalPC= \"192.168.1.10\" # get IPAddress from PC from Wifi connect - It is IP4 address\r\nport4PC=12345 # make sure same on Pico &amp; PC code\r\ntimeAdj =1\r\nssid = 'WIFI_NAME'\r\npassword = 'WIFI_PASSWORD'\r\ndataFileSize=30000 #30,000 bytes (30KB)\r\ndataReadInterval=3 #1 second between readings (in 1 second intervals) so 10 minutes =600\r\nblinkX=.5 #1 second between readings (in 1 second intervals) so 10 minutes =600\r\n\r\n# Set things\r\nmachine.RTC().datetime()\r\nled = machine.Pin('LED', machine.Pin.OUT) #configure LED Pin as an output pin and create and led object for Pin class\r\n\r\n# Connect to Wifi\r\nwlan = network.WLAN(network.STA_IF)\r\nwlan.active(True)\r\nwlan.connect(ssid, password)\r\n\r\nmax_wait = 10\r\nwhile max_wait &gt; 0:\r\n    if wlan.status() &lt; 0 or wlan.status() &gt;= 3:\r\n        break\r\n    max_wait -= 1\r\n    print('waiting for connection...')\r\n    time.sleep(1)\r\n\r\nif wlan.status() != 3:\r\n    raise RuntimeError('network connection failed')\r\nelse:\r\n    print('connected')\r\n    status = wlan.ifconfig()\r\n    print( 'ip = ' + status[0] )\r\n    print('DeviceID= ' + PicoID )\r\n\r\n## Update Time\r\nprint(\"Local time before synchronization: %s\" % str(time.localtime()))\r\n# Synchronize the time with the NTP server\r\nntptime.settime()\r\n# Check the local time after synchronization\r\nprint(\"Local time after synchronization: %s\" % str(time.localtime()))\r\n## Update Time End\r\n\r\n\r\ndef timeNow():\r\n    now = time.localtime()\r\n\r\n    if now[1]&lt;10: #month\r\n        m1=str(now[1])\r\n        m2=(\"0{}\".format(m1))\r\n    #\r\n    if now[2]&lt;10: #day\r\n        d1=str(now[2])\r\n        d2=(\"0{}\".format(d1))\r\n    else:\r\n        d2=now[2]\r\n\r\n    if(now[3]+ timeAdj) &lt;10:  #hr\r\n        h1=str(now[3]+ timeAdj)\r\n        h2=(\"0{}\".format(h1))\r\n    else:\r\n        h2=now[3]\r\n\r\n    if now[4]&lt;10:\r\n        mm1=str(now[4])\r\n        mm2=(\"0{}\".format(mm1))\r\n    else:\r\n        mm2=now[4]\r\n\r\n    if now[5]&lt;10:\r\n        s1=str(now[5])\r\n        s2=(\"0{}\".format(s1))\r\n    else:\r\n        s2=now[5]\r\n\r\n    timeStamp=\"DateTime: {}-{}-{} {}:{}:{}\".format(now[0], m2, d2, h2, mm2, s2)\r\n    return timeStamp\r\n\r\nwith open('savedata.txt', 'a') as f:\r\n    f.write('Test Data Logging on ' + PicoID)\r\n    f.write('\\n')\r\n\r\ndef logData():\r\n# https:\/\/electrocredible.com\/raspberry-pi-pico-w-data-logger-temperature-micropython\/\r\n    file_size=os.stat('\/savedata.txt')\r\n    if(file_size[6]&lt;dataFileSize):\r\n        try:\r\n            with open('savedata.txt', 'a') as f:\r\n                f.write(timeNow())\r\n#                 f.write('Temperature='+ str(temperature_celcius))\r\n                f.write(','+'\\n')\r\n\r\n        except:\r\n                print(\"Error! Could not save\")\r\n\r\ndef dataToLocal(IpLocal, port1, SensData):\r\n        # Create a TCP socket\r\n    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n    # Connect to the PC server (replace with your PC's IP and port)\r\n    s.connect((IpLocal, port1))\r\n#     s.connect((\"192.168.1.10\", 12345))\r\n    # Read sensor data (replace with your specific sensor logic)\r\n    sensor_data = SensData # 'Tuesday 9 January 2024- The rain in spain falls mainly on the plain  '\r\n    # Send sensor data to the PC\r\n    s.sendall(sensor_data.encode())\r\n    # Close the socket connection\r\n    s.close()\r\n    print('Data Sent closed')\r\n\r\n\r\ndef blinkWrite(dataReadInterval):\r\n      led.value(True)  #turn on the LED\r\n      time.sleep(1)   #wait for one second\r\n      led.value(False)  #turn off the LED\r\n      time.sleep(1)   #wait for one second\r\n\r\ndef infoData():\r\n    inf1= PicoID + ','+ timeNow()\r\n    return inf1\r\n\r\n\r\nx=0\r\nwhile True:\r\n    led.value(True)  #turn on the LED\r\n    time.sleep(blinkX)   #wait for one second\r\n    led.value(False)  #turn off the LED\r\n    time.sleep(blinkX)   #wait for one second\r\n    x= x+1\r\n    print(x)\r\n    logData()\r\n    \r\n#     dataToLocal(ip4LocalPC, port4PC, timeNow())\r\n    dataToLocal(ip4LocalPC, port4PC, infoData())\r\n    print(timeNow())\r\n    time.sleep(dataReadInterval)\r\n<\/code><\/pre>\n<h4>And code for Local PC , win10 (in python):<\/h4>\n<pre><code class=\"language-Python\"># ConnectPico2.py\r\n# v2 - try writing data from listener to file\r\n\r\nimport time\r\nimport socket\r\n\r\n# Create a TCP\/IP socket\r\nserver_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n\r\n# Bind the socket to a specific IP address and port\r\nserver_address = (\"0.0.0.0\", 12345)  # Listen on all available IPs, port 12345\r\nserver_socket.bind(server_address)\r\n\r\n# Listen for incoming connections\r\nserver_socket.listen(1)\r\n# Accept incoming connections\r\nwhile True:\r\n    client_socket, client_address = server_socket.accept()\r\n    print(\"Connected by\", client_address)\r\n    try:\r\n        # Receive data in chunks\r\n        while True:\r\n            data = client_socket.recv(1024)  # Receive up to 1024 bytes at a time\r\n            # print(\"y\",data)\r\n            if not data:\r\n                    break\r\n            # Process the received data (e.g., print, store, analyze)\r\n            print(\"Received data:\", data.decode())\r\n            with open('output_data.txt', 'a') as f:  # Open file in append mode\r\n                # try:\r\n                print(\"1\", data)\r\n                f.write(f\"{client_address},{data}\\n\")\r\n                time.sleep(1)  # Adjust interval as needed\r\n    except Exception as e:\r\n        print(f\"Error receiving or processing data: {e}\")\r\n        \r\n    finally:\r\n        # Close the client socket\r\n        client_socket.close()\r\n# Close the server socket when finished\r\nserver_socket.close()\r\n<\/code><\/pre>\n<h3>End comment<\/h3>\n<p>I sent this from Obsidian to WordPress using the WordPress add-in in Obsidian. Which did an OK job but I still needed to do a bit of a tidy up.<\/p>\n<p>Actual code took me a while to get the output to file that I wanted, that took quite a bit of fiddling and testing until I got roughly some of the variables in the output string (eg pico ID). But now that is\u00a0 in the string I can manipulate with something like pandas to tidy up the data.<\/p>\n<p>It might be good to read the stream and then send it to different files based on the ID, so that only data relevant to specific sensors will be sent to a specific file.<\/p>\n<p>you need the Sensor ID as the IP Addree of these devices can change, depending on when they are started and stopped.<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>I sent data from Raspberry Pi Pico W over wifi to local PC. 1. Start listener program on PC and then program on Pico local PC script must be running first, as its listening for the data to come in on all IP addresses but on a specific port Fire up the pico code to [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":9747,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[204],"tags":[483,484],"class_list":["post-9743","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-automation","tag-483","tag-484"],"featured_image_src":"https:\/\/max-drake.cc\/wp-content\/uploads\/2024\/01\/IMG20240103170203-1.png","featured_image_src_square":"https:\/\/max-drake.cc\/wp-content\/uploads\/2024\/01\/IMG20240103170203-1.png","author_info":{"display_name":"Max Drake","author_link":"https:\/\/max-drake.cc\/?author=1"},"_links":{"self":[{"href":"https:\/\/max-drake.cc\/index.php?rest_route=\/wp\/v2\/posts\/9743","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/max-drake.cc\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/max-drake.cc\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/max-drake.cc\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/max-drake.cc\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=9743"}],"version-history":[{"count":3,"href":"https:\/\/max-drake.cc\/index.php?rest_route=\/wp\/v2\/posts\/9743\/revisions"}],"predecessor-version":[{"id":9748,"href":"https:\/\/max-drake.cc\/index.php?rest_route=\/wp\/v2\/posts\/9743\/revisions\/9748"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/max-drake.cc\/index.php?rest_route=\/wp\/v2\/media\/9747"}],"wp:attachment":[{"href":"https:\/\/max-drake.cc\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=9743"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/max-drake.cc\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=9743"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/max-drake.cc\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=9743"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}