We Wired Our Farm Ourselves

We Wired Our Farm Ourselves

Khamarvest is our farm, built by a small founding team, our cows, our work, our mistakes. It has four cameras now. They are live at cam.khamarvest.com, behind a Google login, and the people who put money into this farm can open that page from anywhere and see the cows.

We could have bought an NVR. The shop sells a sealed box: plug the cameras in, plug a monitor in, done. Instead my younger brother Meer Tahmid and I ran the cable ourselves, wired every connection ourselves, and built the whole thing out of parts we understand.

It took longer. It was much more fun. And I learned more about networking in those weeks than in years of writing web apps on top of it. That is the part I want to write down: not the cameras, the network underneath them, and the code that sits on top.

Cow Shed 2, live at cam.khamarvest.com, one click out of the four-camera grid, full resolution

Meer working in the cow shed at night


The whole thing, in plain words

Before any of the technical parts, here is what actually exists now.

Four cameras in the sheds and at the gate. One cable runs to each one, and that single cable carries both the power and the picture, so there is no adapter hanging in the rain at the far end, and nothing extra to fail. All four feed into one small second-hand computer sitting on a shelf in the shed.

That computer does four things. It records everything, and keeps a week. It watches the picture and recognises when a person is there, as opposed to a cow or a moving branch. It puts a webpage on the internet that only invited people can open. And if someone walks into the feed store at two in the morning, it sends a photograph to my phone before I have any way of knowing on my own.

Nothing on the farm is exposed to the internet. The computer reaches out; the internet never reaches in. And if the power cuts, which it does, the whole thing wakes up and repairs itself when the power comes back, and sends a message to say so.

That is the entire system. Everything after this is how it came to exist, how each of those sentences works, and what building it taught me.


Why not just buy the NVR

A retail NVR is a closed appliance. It records, it shows you a grid, and that is the end of the conversation. You cannot ask it to message you on Telegram when someone walks into the feed store at 2 AM. You cannot ask it to tell you that a camera has gone dark. You cannot put your own page in front of it and give five specific people access by email.

More honestly: a box you cannot open teaches you nothing.

So the shape became this, and every arrow is something we had to actually understand:

Dahua IR cameras → PoE switch → farm PC → Frigate (record + detect)
                                        → go2rtc (restream)
                                        → Cloudflare Tunnel → the internet
                                        → Telegram bot (alerts)

Six things moving packets, and I had used three of them before only from a library call.


The moment the screen showed cows

I built the whole thing at home first.

The cameras sat on my desk in Dhaka, pointed at nothing in particular: a wall, a doorway, me walking past. I configured them there, installed Ubuntu Server on the box there, brought up Frigate, the tunnel, the notifier, all of it, against a wall I did not care about. By the time it left the house, every piece had already worked at least once.

Then we carried it to the farm and mounted it for real.

Connected the cable. Powered it up.

And it just worked. First try. The screen filled with our own cows, standing at the feed trough, one lying down, the green of the entrance path in the corner of the frame.

I have shipped a lot of software. Deploys, releases, features going live to users I would never meet. Nothing has ever felt like that. This time the code came out the other side and touched something physical: animals we feed, a shed I have stood in, a farm we built. Programming went through the computer and landed in the world. Shanto, Tushar, Tahmid and I just stood there looking at the screen.

The investors felt it too, and their reaction is my favourite detail in this whole project. Almost all of them are my colleagues and ex-colleagues from software, career engineers. Which means their day now contains this: they set an agentic AI running on some task, and while it writes code, they open another tab and watch cows. Moving, sleeping, eating. The lush green view at the entrance with the palms behind it.

Engineers, waiting on a model, watching a herd. They love it. I have never had a feature received like that.


One cable, and the first three layers

The least glamorous thing in the build is a PoE switch, and it is also where the networking started.

PoE is power over ethernet: the same copper that carries the data carries the electricity. But it is not a dumb wire. Before it sends any power, the switch probes the line and looks for a signature, and it only powers up if there is a real device on the other end. That is why plugging a laptop into a PoE port does not fry it: the port never gets past detection. For us it meant one cable to each camera, no electrician at the shed, no 12V adapter hanging in the rain.

But the switch taught me more than power. Sitting on the shed floor with a laptop, watching ports come up, I got two more layers of the model at once, because on a switch you can watch them happen.

Layer 2: the switch learns who lives where

A switch starts knowing nothing. When the first frame arrives on port 3, it reads the source MAC address, the camera’s permanent hardware identity burned in at the factory, and writes a line in a table: this address lives on port 3.

From then on, a frame addressed to that MAC goes out port 3 and nowhere else. Not the other ports. Not my laptop.

That table is the whole difference between a switch and the old hubs, which simply shouted every frame out of every port and let the machines sort it out. A switch listens, learns, and then stops wasting the wire. It is a tiny learning system built out of one sentence: who talked to me, and where.

And nobody ever configures a MAC table. It fills itself in from traffic, from nothing. I have read about this a dozen times. Watching the table populate itself from a laptop on a shed floor is a different thing.

Layer 3: where a MAC meets an IP

The cameras need to keep the same address, or Frigate loses them the first time the power blinks and DHCP hands out different numbers.

The fix is a DHCP reservation: on the router, you pin an IP to a MAC address. Whoever has this hardware address always gets 192.168.1.x.

That one setting is the whole seam between layer 2 and layer 3 in a single line of config: a permanent hardware identity on one side, a logical, assignable address on the other, and ARP translating between them on every packet. I had read that sentence a hundred times. Watching a camera come back at the same address after a power cut is when it stopped being a sentence.


Everything talks by name, and nothing is published

Every service on that box is a container. Each one gets its own network namespace, its own IP, its own view of the network, and Docker runs a small DNS inside the network so they can find each other by name instead of by address. That is why the config says frigate:5000 and never an IP:

notifier  → http://frigate:5000/api/events     (the Frigate API)
viewer    → http://authgate:8090/viewers       (who is watching)
viewer    → http://frigate:1984/api/           (go2rtc, inside Frigate)
cloudflared → http://viewer:80                 (the page itself)

Four services, four names, no addresses to manage, and the names survive a reinstall because they come from the compose file.

That is the convenient half. The half that matters is the other direction.

Containers on the internal network can reach each other freely. The outside world can reach them only if a port is published to the host, and that is the entire security boundary. Publishing a port is the decision that opens something. Not publishing it means there is nothing to find.

So almost nothing is published. Frigate’s admin UI binds to localhost only:

frigate:
  ports:
    - "127.0.0.1:5001:5000"   # admin UI on localhost only, never the LAN

And the viewer publishes no port at all. cloudflared reaches it as http://viewer:80 on the internal network, which means the only road to that page runs through Cloudflare.

We got this wrong first, and the failure is worth writing down. The early compose file published go2rtc’s RTSP and WebRTC ports on the host. Nothing was using them, and it looked harmless. It was not: it quietly made every camera stream reachable, unauthenticated, by anything on the farm network. Those lines are gone, and there is now a comment in the file explaining why they are gone, so that neither of us puts them back for convenience.


Frigate, and pulling the stream only once

Every camera sends out two pictures of the same scene at once: a big sharp one and a small rough one. That sounds wasteful. It is the single cleverest thing in the build, and it is free.

Each camera speaks RTSP. It is worth knowing that RTSP is mostly a remote control, not the video itself: the client sends DESCRIBE, SETUP, PLAY, and the actual frames arrive as RTP alongside it. The camera’s URL takes a subtype parameter, and that little number matters more than it looks:

  • subtype=0, the main stream, full resolution. Used for recording and for fullscreen.
  • subtype=1, the sub stream, small and cheap. Used for the four-up grid and for object detection.

Cameras generate both themselves, for free. Detecting cows and people on a low-res stream costs a fraction of the computer’s effort and finds exactly the same cow. You do not need a sharp picture to notice that a person is standing in a doorway. You only need it once you want to know who.

Frigate does the recording and the detection. Recording is a stream copy. The camera already encoded H.264, so we write those bytes straight to disk rather than decoding and re-encoding them. Seven days retained, oldest deleted automatically. The one place the CPU does touch the video is decoding for detection, and that runs on the Intel iGPU through VAAPI, which is the difference between four cameras running comfortably and an i3 pinned at 100%.

Bundled inside Frigate is go2rtc, which solves the problem I had not thought about: what happens when four people open the page at once. Without it, every viewer opens their own RTSP session against the camera, and a small IP camera falls over at about three. go2rtc pulls each camera once and fans that one pull out to as many browsers as ask for it. It is a reverse proxy for video, and it is the reason the page scales past my brother and me.


Getting it out to the internet without opening a single port

The farm’s internet is an ordinary connection. No static IP, no business plan, and I am not going to punch a port-forward through to a camera system on a farm I cannot reach in twenty minutes.

Cloudflare Tunnel removes the question. cloudflared runs on the farm PC and dials outbound to Cloudflare, and it holds that connection open. Traffic for cam.khamarvest.com arrives at Cloudflare’s edge and comes back down the pipe the farm already opened, and the TLS is terminated at the edge.

The router has no inbound ports open at all. There is nothing at the farm’s IP address to find, port-scan, or brute force. The most secure port really is the one that does not exist. That sentence took me years to feel, and one evening of nmap from outside to finally believe.

The latency tradeoff nobody warns you about

Here is the honest cost, and it is a nice lesson in transport protocols.

Plainly: safety made the video about a second slower, and a second is a price worth paying. The reason why is the interesting part.

WebRTC, the thing that makes video calls feel instant, needs UDP. The tunnel serves HTTPS over TCP. So WebRTC’s UDP simply cannot make the trip, and the player falls back a rung.

TransportLatencySurvives the tunnel
WebRTC (UDP)0.1–0.5 s✗
MSE (TCP)0.5–1.5 s✓
LL-HLS (TCP)2–4 s✓
HLS (TCP)5–10 s✓

The viewer page uses go2rtc’s player, which negotiates down that list by itself and lands on MSE, around one second through the tunnel. For watching cows, one second is indistinguishable from live.

The satisfying part: when I open the same page over Tailscale instead, UDP works, WebRTC wins the negotiation, and it drops to ~0.3 s. Same HTML, same server, no flags. The network conditions choose the protocol, and the page just adapts. I did not write a line of that negotiation. I just learned to read it.


Who gets in

Login is Cloudflare Access, sitting in front of the tunnel. An investor signs in with Google; if their email is not on the policy, they never reach the farm at all. The rejection happens in Cloudflare’s network, long before any packet touches the farm PC.

Think of it as a doorman who checks the guest list in the street outside, before anyone reaches the building.

Once a request passes, Access stamps a header onto it: Cf-Access-Authenticated-User-Email. Every location in our nginx config refuses any request arriving without it.

location = /api/viewers {
    if ($http_cf_access_authenticated_user_email = "") { return 403; }
    proxy_pass http://authgate:8090/viewers;
}

That is belt-and-braces, since anything that somehow reached nginx without passing Access gets a 403. But writing that rule is what forced me to understand why the header is safe to trust, because a header is just text someone put in a request. The answer is the tunnel: nothing can reach nginx except through Cloudflare, so nothing can forge the header. Trust a header a user could set themselves and you have built a lock with the key taped to it.

The streaming path needs one more nginx detail, and it tripped me up for an afternoon: the MSE player talks to go2rtc over a WebSocket, and a reverse proxy will not carry a WebSocket unless you upgrade the connection explicitly.

location /api/ {
    if ($http_cf_access_authenticated_user_email = "") { return 403; }
    proxy_pass http://frigate:1984/api/;
    proxy_http_version 1.1;
    proxy_set_header Upgrade    $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_buffering off;
}

Without those three lines the page loads, the grid populates, and the video never starts, with no obvious error. proxy_buffering off matters too: a buffered proxy sits on the frames and turns a live stream into a delayed one.

The last touch is a small presence service, authgate, which reads that same email header and remembers who is watching. It is almost nothing:

def _identity(self):
    email = self.headers.get("Cf-Access-Authenticated-User-Email", "")
    return email.strip().lower() or None

A request without the header gets a 401 and is not tracked, which means the widget cannot be fooled by someone hitting the service directly. The page shows who else is watching right now, and when an investor opens the cam, the Telegram group gets a line: someone started watching the farm cam. One of them is in Malaysia, a brother from JoulesLabs who I was introduced to, and when his name appears at odd hours, the farm feels a great deal less remote than it is.


The Telegram guard

This is the part a retail NVR was never going to give me, and the part I am proudest of.

It is a small Python service, standard library only, and it polls Frigate’s event API and sends alerts to a Telegram group with the snapshot attached.

The naive version of this is unusable. A person standing in the entrance generates events continuously, and your phone buzzes forty times. So the notifier is a state machine per camera, not an event forwarder. Each camera carries a small dict of what it currently believes:

{
    "occupied": False,       # is someone there right now?
    "first_seen": 0,         # when this presence session started
    "last_seen": 0,          # most recent detection
    "last_alert_time": 0,    # when we last bothered the group
    "alert_count": 0,        # alerts sent this session
}

And the decision, which is the whole idea in ten lines:

def _detect_alert_type(state, now, loiter_realert):
    if not state["occupied"]:
        return "entry", True      # first entry, or a re-entry after the area cleared
    if loiter_realert <= 0:
        return "", False          # this camera does not do loiter re-alerts
    if now - state["last_alert_time"] >= loiter_realert:
        return "loiter", True     # still there, and still there long enough to matter
    return "", False              # still inside the window, stay quiet

The state clears itself after a gap:

if st["occupied"] and now - st["last_seen"] >= CLEAR_GAP:   # 60s of silence
    st["occupied"] = False

So the four transitions are entry, loiter, clear, and re-entry (which is just an entry after a clear, and gets a fresh alert because leaving and coming back is not the same as standing still).

And the rules differ per camera, because the farm differs per camera:

CAM_RULES = {
    "entrance":   {"labels": ["person", "car", "truck"], "night_only": False, "loiter_realert": 180},
    "feed_store": {"labels": ["person"],                 "night_only": False, "loiter_realert": 300},
    "cow_shed_1": {"labels": ["person"],                 "night_only": True,  "loiter_realert": 0},
    "cow_shed_2": {"labels": ["person"],                 "night_only": True,  "loiter_realert": 0},
}

A person in a cow shed at 11 AM is a farmhand doing his job. The same person at 2 AM is the only message I want to receive that night.

Watching the watchman

Any monitoring system has one obvious failure mode: it fails, and by failing, stops telling you anything. Silence looks exactly like peace.

So the notifier also watches itself:

  • A camera reporting 0 fps for 90 seconds → camera offline: check power, network, or tampering.
  • Frigate unreachable for 3 minutes → recording and detection may be down.
  • Disk below 15% free → warn, once a day, before old recordings start getting deleted.
  • A daily heartbeat: 4/4 cameras online, storage 62% free. Boring by design. Its whole job is to prove the alert pipe still works on the days nothing happens.

But none of that can survive the farm PC dying, or the power going, or the internet dropping. A dead machine cannot report that it is dead. So the notifier also pings a healthchecks.io URL every five minutes. If those pings stop, healthchecks.io alerts me from the outside. A dead man’s switch. The absence of a message becomes the message.

And when something is genuinely stuck, I can send /reboot to the bot. Only my personal Telegram user ID is accepted; everyone else’s is logged and ignored. The container cannot reboot the host, and it should not, so it does the honest thing instead of asking for a privilege it does not need: it writes a timestamp into a file in a volume shared with the host.

with open(REBOOT_REQUEST_FILE, "w") as f:   # container side: write a request
    f.write(str(now))

And a one-line cron job on the host picks it up within the minute and reboots:

REQUEST_FILE="/home/khamarvest/farm-cam/ipc/reboot_request"
if [ -f "$REQUEST_FILE" ]; then
    rm -f "$REQUEST_FILE"
    /sbin/reboot
fi

The privilege stays on the host side of the wall, and the container only ever writes a file. Fixing the farm from my phone in Dhaka never gets old.

Push-to-talk goes the other way, and it closes the loop from browser to shed: the page opens a WebSocket, streams raw PCM through it, and a small service on the host pipes those bytes straight into ffplay, which plays them out of a USB speaker in the shed. Hold the button, talk to whoever is out there.


The boring hardware that makes it real

The first version ran on my MacBook, sitting in the shed, plugged in. That is a demo, not infrastructure.

It now lives on a Dell OptiPlex 9020 Micro, a used office desktop, i3, 8 GB of RAM. A 120 GB SSD for the OS and Frigate’s database, a 1 TB HDD for recordings only.

Two settings do most of the heavy lifting. BIOS → AC Recovery → Power On, so that when village power cuts and returns, the box boots itself, Docker comes up, and every container restarts on its own. Then a “Farm guard online” message lands in Telegram, and I know the farm healed itself while I was asleep. And the VAAPI decode above, which is what keeps the i3 cool.

Backups run nightly: a consistent snapshot of Frigate’s SQLite database taken with SQLite’s own online backup API, safe while it is running, no stopping anything, plus every config file, seven archives retained. The recordings are deliberately not backed up. They are seven-day rolling footage; the event clips are the evidence that matters, and a terabyte of cows sleeping is not worth protecting.


ssh farm

The box runs Ubuntu Server 24.04. No desktop, no monitor, no keyboard. It sits on a shelf in the shed with two cables in it, power and ethernet, and that is the entire physical interface. If you walked past it you would think somebody left an old office computer behind.

Two lines in ~/.ssh/config on my Mac:

Host farm
    HostName <the box>
    User khamarvest

And now the farm is a word.

ssh farm

I still find this genuinely wonderful. I type four letters at a café table in Dhaka, and the prompt changes, and I am standing inside a machine in a cow shed in the village. Same terminal, same font, same muscle memory as any other server I have ever worked on. The cows are forty kilometres away and I can read the logs of the thing that is watching them.

Everything is dockerized, which means the farm has no secrets and no snowflakes. Every service is a few lines in one docker-compose.yml in a git repo, and the code is mounted read-only into the containers, so editing the alert rules does not even need a rebuild:

notifier:
  volumes:
    - ./notifier:/app:ro   # code edits go live on restart, no rebuild
    - ./ipc:/ipc           # shared with the host reboot-watcher

When I decided the cow sheds should only alert at night, that was one line in CAM_RULES and one docker compose restart notifier, from my bed.

Updating the farm is the same motion as updating any project I have ever shipped:

ssh farm
cd farm-cam
git pull
docker compose up -d

Ten seconds, and the cameras never stop watching.

And because it is all a git repo plus one .env file that never leaves the farm, the box is disposable. If that OptiPlex died tomorrow, a fresh machine would be an evening’s work: install Ubuntu, install Docker, clone, copy the .env, docker compose up -d. The farm’s brain is not in the hardware. The hardware is just where it happens to be running this month.

That is the part that still makes me grin. A farm, mud and feed and animals, the oldest work there is, now has a deploy pipeline.


What comes next

The cameras are the first sensor, not the last one. What I actually want is for the farm to report itself, and I want to write that code myself.

The one I am chasing first is weight, without the weighing.

Traditional scales mean pushing an animal onto a platform, which is work, which means it happens rarely, which means you find out too late that one cow stopped gaining. Instead: a load cell built into a walkway they already use. The cow walks over on her own, and the software records the weight. Do that daily and weight gain becomes a graph instead of a guess, and a cow going off her feed shows up in the data days before it shows up to the eye.

That is the direction. Traditional farming underneath, sensors on top, and every layer of it something we built and can open up.

I intend to document those moments as they happen, the same way as this one.


What it actually taught me

I write software for a living. I have used sockets, and load balancers, and HTTP for years, always from comfortably above.

Doing it with my hands, that stack came apart into things I could touch, and almost none of them were in the cameras.

A switch that learns from traffic which MAC is on which port, and then stops shouting. A reservation binding a hardware identity to an address, with ARP translating on every packet. A DNS that lives inside a compose file, so frigate:5000 resolves to a container instead of a machine. A boundary that is one boolean per port: published or not, and nothing between. A tunnel that can only ever be opened from the inside, because there is no outside door. UDP that cannot survive a TCP pipe, and a player that walks down a table and settles for the best transport that does. A header that is only trustworthy because of what cannot reach the thing that reads it. A WebSocket that needs three lines of nginx to exist at all.

That is the whole OSI model, and I did not learn it from a diagram. I learned it from a cable I ran myself, into a port that lit up in a cow shed.

The best part is where it ended up. The people who backed this farm are scattered across countries, and a farm is the least legible thing in the world to someone who cannot visit it. Now they open a link and see the cows breathing.

Trust, delivered over a wire we pulled ourselves.


Everything here is open: github.com/mmestiyak/khamarvest-cam. Khamarvest is our farm, and our page: facebook.com/khamarvest.

If you came for the farming rather than the packets: the farm says what we are doing out there, and what I am working on now is the short version of everything I am chasing this season.

Written by . Software engineer from Bangladesh. I ship products end to end, from the browser to the board: code generation, firmware and PCB tooling at IDEEZA, and my own products ProcureIndex, Akhra and Kommercly. Also farms, cycles and fights MMA.

Published

Get new logs by email. No spam, unsubscribe anytime.